Man*_*kar 18 c# wpf button mvvm icommand
我如何发送多个参数来自Button
于WPF
?我能够发送TextBox
正确值的单个参数.这是代码.
XAML
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="133,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Button" Grid.Row="1" Height="23" Command="{Binding Path=CommandClick}" CommandParameter="{Binding Text,ElementName=textBox1}" HorizontalAlignment="Left" Margin="133,62,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
Run Code Online (Sandbox Code Playgroud)
Code behind
public ICommand CommandClick { get; set; }
this.CommandClick = new DelegateCommand<object>(AddAccount);
private void AddAccount(object obj)
{
//custom logic
}
Run Code Online (Sandbox Code Playgroud)
Ron*_*B.I 31
除了使用在您的类中定义属性的方法(让我们称之为您的ViewModel)由您的视图绑定,有时(不常见)我们不想这样做,这是一个重要的工具,可以在这些情况是MultiBinding,所以为了完整起见,即使你对第一个选项感到满意,我还会介绍另一种方法.
所以回答你的问题:
1. MVVM方法:
使用MVVM方法并定义视图绑定的属性,并在ViewModel命令中使用这些属性,而无需CommandParameters.
2. MultiBinding :( 可以幸福地使用MVVM方法)
将命令参数作为Multi Binded参数传递,如下所示:
<Button Content="MultiBindingExample" Command="{Binding MyCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MyMultiConverter}">
<Binding Path="..." ElementName="MyTextBox"/>
<Binding Path="..." ElementName="MySomethingElse"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
Run Code Online (Sandbox Code Playgroud)
使用IMultiValueConverter
接口定义转换器:
public class MyMultiConverter: IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
}
Run Code Online (Sandbox Code Playgroud)
并且用于提取值:只需将命令中的参数作为参数引用,Object[]
并按照与MultiBinding中相同的顺序使用参数.
Ree*_*sey 14
如何从wpf中的按钮发送多个参数.
您只能发送一个参数作为CommandParameter
.
更好的解决方案通常是将TextBox
View控件和其他控件绑定到ViewModel中的多个属性.然后该命令可以访问所有这些属性(因为它在同一个类中),根本不需要命令参数.