更新源触发器按钮单击转换器
本文关键字:单击 转换器 按钮 触发器 更新 | 更新日期: 2023-09-27 17:55:15
使用以下代码,当更新/更改其中一个依赖项属性时,将调用转换方法。
我希望仅在单击按钮时调用转换器。我该怎么做?
代码如下:
<Button Content="Create Project">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MyConverter}" UpdateSourceTrigger="Explicit" Mode="TwoWay">
<Binding Path="Text" ElementName="txtDesc"/>
<Binding Path="Text" ElementName="txtName"/>
<Binding Path="SelectedItem" ElementName="ListBox"/>
<Binding Path="SelectedItem.Language" ElementName="TreeView"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
我认为
会纠正类似以下代码的内容:
XAML
<Button Content="Create Project" Click="Button_Click"/>
.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
string param1 = txtDesc.Text;
string param2 = txtName.Text;
object param3 = ListBox.SelectedItem;
object param4 = TreeView.SelectedItem;
object convertResult = MyConverterUtils.Convert(param1, param2, param3, param4);
(sender as Button).CommandParameter = convertResult;
//or you can execute some method here instead of set CommandParameter
}
public class MyConverterUtils
{
//convert method
//replace Object on your specific types
public static Object Convert(string param1, string param2,Object param3,Object param4)
{
Object convertResult=null;
//convert logic for params and set convertResult
//for example convertResult = (param1 + param2).Trim();
return convertResult;
}
}
使用 MVVM 可以非常简单:
- 使用 RelayCommand 在 MVVM 中声明
ICommand
。 - 将按钮的
Command
属性绑定到声明的命令。 - 在命令的执行方法中执行逻辑。
- 更新所需的属性。
视图模型
public class MyViewModel : INotifyPropertyChanged
{
public ICommand UpdateSomething { get; private set; }
public MyViewModel()
{
UpdateSomething = new RelayCommand(MyCommandExecute, true);
}
private void MyCommandExecute(object parameter)
{
// Your logic here, for example using your converter if
// you really need it.
// At the end, update the properties you need
// For example adding a item to an ObservableCollection.
}
}
XAML
<Button Content="Create Project" Command="{Binding UpdateSomething}"/>