【问题标题】:WPF ComboBox SelectionChanged event to command not firingWPF ComboBox SelectionChanged 事件命令未触发
【发布时间】: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,如果是这样,请发布触发您正在谈论的事件的代码(在加载视图之后)。

标签: wpf mvvm combobox


【解决方案1】:

SelectedValue 绑定到视图模型上的Property

Property set{...} 块中执行您的逻辑或调用

ListTypeComboSelectionChangedCmdExec(value)

Binding ComboBox SelectedItem using MVVM

【讨论】:

  • 这是一个聪明的解决方案,但我更愿意保持二传手清洁。此外,我更想知道为什么这样的功能不起作用,SelectionChanged 事件在哪里触发但它不执行底层命令。还是谢谢。
  • 为什么不将 SelectedValue 绑定到 Property,而是在您的视图 OnLoaded 事件处理程序中,将其设置为第一个值。设置器逻辑是次优的
  • @Lucifer 回复有点晚,但我的猜测是事件在行为被“附加”之前被触发。
【解决方案2】:

就我而言,我在后面的代码中使用处理程序并将其连接到 ModelView,如下所示。

var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
    viewModel.MyCommand.Execute(null);

请查看此链接:Call Command from Code Behind

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多