笔记03 wpf 在MVVM模式下怎样在Viewmodel里面获得view的控件对象
标签:
转自MVVM中轻松实现Command绑定(二)传递Command参数
属性栏里去设置的。语句应该是CommandParameter="{Binding ElementName=控件名}"
我们如果需要在Command中传递参数,实现也很简单。DelegateCommand还有一个DelegateCommand<T>版本,可以传递一个T类型的参数。
1.View的Button绑定,其中CommandParameter定义了一个“20”的参数
[html] view plaincopy
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication1"
Title="Window1" Height="193" Width="190">
<Window.DataContext>
<vm:Window1ViewModel />
</Window.DataContext>
<Grid>
<Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="34,20,0,0" Name="button1" VerticalAlignment="Top" Width="109"
Command="{Binding ButtonCommand}"
CommandParameter="20"/>
</Grid>
</Window>
2.ViewModel定义命令,注意委托参数
[csharp] view plaincopy
namespace WpfApplication1 {
public class Window1ViewModel {
public ICommand ButtonCommand {
get {
return new DelegateCommand<string>((str) => {
MessageBox.Show("Button‘s parameter:"+str);
});
}
}
}
}
并且,特殊情况下,,我们可以将控件对象作为参数传递给ViewModel,注意{Binding RelativeSource={x:Static RelativeSource.Self}}是绑定自己(Button)的意思。
[html] view plaincopy
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication1"
Title="Window1" Height="193" Width="190">
<Window.DataContext>
<vm:Window1ViewModel />
</Window.DataContext>
<Grid>
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67500.html