【发布时间】:2014-05-02 09:11:29
【问题描述】:
我有一个 ComboBox 的以下 XAML,它有一个代码隐藏 SelectionChanged 事件处理程序和 ViewModel 的另一个 Command 属性。我已将SelectedIndex 属性设置为0。现在,当我运行项目时,将调用代码隐藏处理程序,但不执行Command。我想要的是第一次加载视图时应该为SelectedIndex=0 执行Command。
<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 处理程序:
private void ListTypeComboSelectionChangedCmdExec(string listType) { }
【问题讨论】:
-
为什么要这样做?如果您希望在视图加载后立即发生某些事情,为什么不在加载时执行它when?此外,在创建时(不是运行时),不会为在 xaml 中设置的 SelectedIndex 触发任何事件。
-
你有一个事件和一个命令用于同一件事。摆脱内联事件调用。
-
@Sinity,如果第一个 ComboBoxItem 的 selectionchanged 事件在视图加载后立即触发,那么为什么不应该执行命令?
-
@Xcalibur37,即使我删除了 SelectionChanged 事件处理程序,该命令也不会执行。
-
@Lucifer,如果是这样,请发布触发您正在谈论的事件的代码(在加载视图之后)。