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

16 篇文章 5 订阅
3 篇文章 1 订阅

我们如果需要在Command中传递参数,实现也很简单。DelegateCommand还有一个DelegateCommand<T>版本,可以传递一个T类型的参数。

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

<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定义命令,注意委托参数

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)的意思。

<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"/>
		<Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="34,85,0,0" Name="button2" VerticalAlignment="Top" Width="109"
				Command="{Binding ButtonCommand2}"
				CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"/>
	</Grid>
</Window>

再看ViewModel

namespace WpfApplication1 {
	public class Window1ViewModel {

		public ICommand ButtonCommand {
			get {
				return new DelegateCommand<string>((str) => {
					MessageBox.Show("Button's parameter:"+str);
				});
			}
		}

		public ICommand ButtonCommand2 {
			get {
				return new DelegateCommand<Button>((button) => {
					button.Content = "Clicked";
					MessageBox.Show("Button");
				});
			}
		}
	}
}


这样就可以在委托中获取Button对象了。但是MVVM本身比建议ViewModel操作View。

下一次,我将介绍一种更强大的命令绑定,可以用于各种事件的ViewModel触发。好了,下次见!

  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在 WPF 应用程序,使用 MVVM 模式时,常用的命令绑定方式是通过 RelayCommand,它是一个实现了 ICommand 接口的类,可以将其绑定到视图模型的命令属性上。 下面是 RelayCommand 的使用示例: 首先,定义一个 RelayCommand 类: ```csharp public class RelayCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; public RelayCommand(Action execute) : this(execute, null) { } public RelayCommand(Action execute, Func<bool> canExecute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(); } public void Execute(object parameter) { _execute(); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } ``` 这里的 RelayCommand 类有两个构造函数,第一个只接受一个 Action 类型的参数,用来执行命令;第个构造函数接受一个 Func<bool> 类型的参数,用来判断命令是否可执行。在 CanExecute 方法,如果 _canExecute 不为 null,就会调用它来判断命令是否可执行。 接下来,在视图模型定义一个 RelayCommand 类型的属性,并在需要执行命令的方法调用它: ```csharp public class MainViewModel : ViewModelBase { private readonly IDataService _dataService; public MainViewModel(IDataService dataService) { _dataService = dataService; LoadDataCommand = new RelayCommand(LoadData); } public ICommand LoadDataCommand { get; private set; } private void LoadData() { // 加载数据 } } ``` 最后,在 XAML 绑定命令: ```xml <Button Content="Load Data" Command="{Binding LoadDataCommand}" /> ``` 这里的 Command 属性绑定到视图模型的 LoadDataCommand 属性上,当按钮被点击时,就会执行 LoadData 方法。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值