您的位置:首页 > 其它

MVVM中轻松实现Command绑定(二)传递Command参数

2013-02-05 21:38 423 查看
我们如果需要在Command中传递参数,实现也很简单。DelegateCommand还有一个DelegateCommand<T>版本,可以传递一个T类型的参数。

1.View的Button绑定,其中CommandParameter定义了一个“Baby”的参数

<Window x:Class="MVVMCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMCommand"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Button Content="Button" Command="{Binding ButtonCommand}"
CommandParameter="Baby"/>
</Grid>
</Window>
2.ViewModel定义命令,注意委托参数

namespace MVVMCommand{
public class MainWindowViewModel{

public ICommand ButtonCommand{
get{
return new DelegateCommand<string>(new Action<string>((str) =>{
MessageBox.Show("Button's parameter: " + str);
}));
}
}
}
}
并且,特殊情况下,我们可以将控件对象作为参数传递给ViewModel,注意{Binding RelativeSource={x:Static RelativeSource.Self}}是绑定自己(Button)的意思。

<Window x:Class="MVVMCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMCommand"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Button Content="Button" Command="{Binding ButtonCommand}"
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"/>
</Grid>
</Window>
再看ViewModel

namespace MVVMCommand{
public class MainWindowViewModel{

public ICommand ButtonCommand{
get{
return new DelegateCommand<Button>(new Action<Button>((btn) =>{
btn.Content = "Clicked";
}));
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: