英文:
How to add selectionchanged/dropdownopened to combobox via ICommand/EventTrigger in MVVP WPF
问题
我正在使用MVVM模式构建一个程序。我可以在xaml.cs文件中的非MVVM方式处理selectionchanged事件的方法。但是我不知道在MVVM中如何做到这一点。
目前,我的所有ICommand属性都在viewmodel.cs文件中,视图代码如下:
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10,0" HorizontalAlignment="Right">
<Label Content="Ports" Margin="2" />
<ComboBox IsReadOnly="True" AllowDrop="True" x:Name="ComboBox_SerialPort" MinWidth="60" Margin="5"
ItemsSource="{Binding SerialPortList}" SelectedValue="{Binding SelectedSerialPort}"
SelectionChanged="{Binding Cmd_ComboBox_SerialDropDownSelectionChanged}">
</ComboBox>
</StackPanel>
显然,直接将ICommand属性绑定到SelectionChanged不起作用。但是ComboBox控件中没有Command属性。那么,我如何将ICommand附加到控件事件中呢?
谢谢
英文:
I'm building a program with MVVM pattern
I can handle selectionchanged event with method in xaml.cs file in non-MVVM way. but don't know how to do this in MVVM.
Currently all my ICommand properties are in viewmodel.cs file, and view code like below
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10,0" HorizontalAlignment="Right">
<Label Content="Ports" Margin="2" />
<ComboBox IsReadOnly="True" AllowDrop="True" x:Name="ComboBox_SerialPort" MinWidth="60" Margin="5"
ItemsSource="{Binding SerialPortList}" SelectedValue="{Binding SelectedSerialPort}"
SelectionChanged="{Binding Cmd_ComboBox_SerialDropDownSelectionChanged}" >
</ComboBox>
</StackPanel>
Apparently directly binding ICommand property to SelectionChanged is not working. but there's no Command property in Combobox control. So how do I attach ICommand to control events
Thanks
答案1
得分: 1
你可以在 SelectedSerialPort
源属性的 setter 中处理你的选择更改逻辑,该属性会在你在 ComboBox
中选择一个值时被设置。
英文:
You could handle your selection changed logic in the setter of the SelectedSerialPort
source property which will get set when you select a value in the ComboBox
.
答案2
得分: 0
Option 1:
<ComboBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding YourCommandName}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
Option 2:
<ComboBox SelectedValue="{Binding SelectedSerialPort, UpdateSourceTrigger=PropertyChanged}"/>
英文:
Option 1:
<ComboBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding YourCommandName}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Combobox>
Option 2:
<ComboBox SelectedValue="{Binding SelectedSerialPort, UpdateSourceTrigger=PropertyChanged}"/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论