WPF委托命令DelegateCommand的傳參方式


首先引用  Microsoft.Practices.Prism

MVVM模式代碼如下:

XAML代碼:

<!-- 無參方式 -->
<Button Content="Test Command" Command="{Binding TestCommand}" />

<!-- 將自己作為參數 -->
<Button Content="Test Command2" Command="{Binding TestCommand2}" CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}" >

<!-- 將父元素作為參數 -->
<Button Content="Test Command3" Command="{Binding TestCommand3}" CommandParameter="{Binding RelativeSource={x:Static RelativeSource.TemplatedParent}}" >

后台代碼:

// code-behind構造函數中添加:

this.DataContext = new ViewModel();

ViewModel代碼:

// ViewModel 構造函數
public ViewModel()
{    CallCOmmand1 = new DelegateCOmmmand(Call1);
    CallCOmmand2 = new DelegateCOmmmand<Object>(Call2);
    CallCOmmand3 = new DelegateCOmmmand<Object>(Call3);
}

// 命令聲明
public DelegateCommand CallCommand { get; private set; }
public DelegateCommand<Object> CallCommand2 { get; private set; }
public DelegateCommand<Object> CallCommand3 { get; private set; }

// 命令實現
public void Call1()
{
}

public void Call2( Object obj )
{
    Button button = obj as Button;
}

public void Call3( Object obj )
{
    ParentType parent = obj as ParentType;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM