我有一个ComboBox
的XAML,它有一个代码隐藏的SelectionChanged
事件处理程序和ViewModel的另一个Command属性。我已将SelectedIndex
属性设置为0.现在,当我运行项目时,将调用代码隐藏处理程序,但不会执行Command
。我想要的是,第一次加载View时应该为Command
执行SelectedIndex=0
。
<ComboBox Name="listComboBox" SelectionChanged="listComboBox_SelectionChanged" SelectedIndex="0" SelectedValuePath="Content" Margin="5,0" Height="35" Width="150" VerticalAlignment="Center" HorizontalAlignment="Left">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding ListTypeComboSelectionChangedCmd}" CommandParameter="{Binding ElementName=listComboBox, Path=SelectedValue}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ComboBoxItem Content="ItemOne" />
<ComboBoxItem Content="ItemTwo" />
<ComboBoxItem Content="ItemThree" />
</ComboBox>
更新
代码隐藏事件处理程序:
private void listComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { }
ICommand对象:
public ICommand ListTypeComboSelectionChangedCmd
{
get { return new RelayCommand<string>(ListTypeComboSelectionChangedCmdExec); }
private set;
}
ICommand Handler:
private void ListTypeComboSelectionChangedCmdExec(string listType) { }
在视图模型上将SelectedValue
绑定到Property
。
在Property
set{...}
区块做你的逻辑或打电话
ListTypeComboSelectionChangedCmdExec(value)
这是一个很老的问题,但我会回答以后感兴趣的人。
在我的例子中,我在代码中使用处理程序并将其连接到ModelView,如下所示。
var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
viewModel.MyCommand.Execute(null);
请检查以下链接:Call Command from Code Behind