WPF ComboBox EventTrigger 改变其他控件的值 - 使用数据绑定和 MVVM
可以使用 WPF 中的数据绑定和 MVVM 模式来实现 ComboBox 的 EventTrigger 改变其他控件的值。
首先,在 ViewModel 中定义绑定的数据属性和 Command。例如:
public class MyViewModel : INotifyPropertyChanged
{
private string selectedValue;
public string SelectedValue
{
get { return selectedValue; }
set
{
selectedValue = value;
OnPropertyChanged(nameof(SelectedValue));
}
}
public ICommand SelectionChangedCommand { get; set; }
public MyViewModel()
{
SelectionChangedCommand = new RelayCommand(SelectionChanged);
}
private void SelectionChanged()
{
// do something when combobox selection changed
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后,在 XAML 中使用数据绑定将 ComboBox 的 SelectedValue 绑定到 ViewModel 的 SelectedValue 属性上,并使用 EventTrigger 触发 Command 执行操作。例如:
<Window.DataContext>
<local:MyViewModel/>
</Window.DataContext>
<StackPanel>
<ComboBox ItemsSource="{Binding SomeList}" SelectedValue="{Binding SelectedValue}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
<TextBox Text="{Binding SelectedValue}"/>
</StackPanel>
这样,当 ComboBox 的 SelectedValue 值改变时,ViewModel 中的 SelectionChanged 方法会被执行,可以在该方法中改变其他控件的值。同时,其他控件的值与 ViewModel 中的 SelectedValue 属性进行了双向数据绑定,当 SelectedValue 改变时,其他控件的值也会跟随改变。
原文地址: https://www.cveoy.top/t/topic/nhU7 著作权归作者所有。请勿转载和采集!