【WPF】改变combobox在选项的时候触发一个方法
需求:实现一个combobox在改变选项的时候,触发一个方法。使用binding的方式进行实现。
实现:在WPF框架里,采用绑定的方式达成当ComboBox选项改变时触发方法的目的。具体做法是借助SelectedItem或者SelectedValue属性绑定,再搭配ICommand接口达成命令绑定。
代码:
ViewModel.cs
private void OnSelectionChanged(string selectedItem)
{
// 这里是选项改变时要执行的方法
// 可以根据 selectedItem 进行相应的操作
}
MainWindow.xaml
<ComboBox ItemsSource="{Binding ComboBoxItems}"
SelectedItem="{Binding SelectedItem1, Mode=TwoWay}"
HorizontalAlignment="Left" Width="120">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
问题:
需要使用 NuGet 包安装 Microsoft.Xaml.Behaviors.Wpf。
操作步骤:
1.安装NuGet包:
在Visual Studio中,右键点击项目,选择 “管理 NuGet 包”。
在 “浏览” 选项卡中搜索Microsoft.Xaml.Behaviors.Wpf,然后安装该包。
2.修改XAML命名空间:
在窗口的UI元素和布局中添加:
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"。

浙公网安备 33010602011771号