c# - 在 WPF 中将命令绑定(bind)到 ComboBoxItem

标签 c# wpf combobox

我有一个简单的组合框,我想在每次所选值更改时触发单独的命令。这是我的标记示例:

<WrapPanel Grid.Row="0" Visibility="{Binding ShowToggleViewFeedViewManual}">
    <ComboBox Margin="3,3,0,0">
        <ComboBoxItem IsEnabled="{Binding CanSelectViewFeedData}" >
            <ComboBoxItem.CommandBindings>
                <CommandBinding Command="SelectViewFeedDataCommand" />
            </ComboBoxItem.CommandBindings>
            <TextBlock Text="View Feed Data"/>
        </ComboBoxItem>
        <ComboBoxItem IsEnabled="{Binding CanSelectViewManualData}">
            <ComboBoxItem.CommandBindings>
                <CommandBinding Command="SelectManualFeedDataCommand" />
            </ComboBoxItem.CommandBindings>
            <TextBlock Text="View Manual Data"/>
        </ComboBoxItem>
    </ComboBox>
</WrapPanel>   

我收到一条错误消息“无法转换‘SelectViewFeedDataCommand’”。对于其他 ComboBoxItem,我也收到类似的错误。 ICommand 在 ViewModel 类中定义,该类是 UserControl 的数据源,绑定(bind)为 DataTemplate。

public ICommand SelectViewFeedDataCommand
{
    get
    {
        // Code to perform
    }
}

我对此进行了相当广泛的研究,但没有找到如何有效地将 ICommand 绑定(bind)到 ComboBoxItem 的答案。

我正在从使用一组单选按钮和相关命令的现有代码中改编它,这很容易完成。使用 ComboBox 没有简单的方法来做到这一点吗?

谢谢。

最佳答案

您是否尝试过将命令放入绑定(bind)?

<CommandBinding Command="{Binding SelectManualFeedDataCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />

编辑更新策略:

由于 ComboBox 项不支持直接命令绑定(bind),请尝试创建附加属性:

Link

关于c# - 在 WPF 中将命令绑定(bind)到 ComboBoxItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11615334/

相关文章:

c# - 转换 linq-to-sql 的结果

wpf - WPF 是我应用程序的安全选择吗?

c# - ContinueWith() 直到主机进程结束才执行

javafx - 选择组合框项目时执行操作 FXML

c# - 我可以在 C# 泛型约束中指定 'supertype' 关系吗?

c# - ssl 照片问题

c# - 使用 C# 或任何开源文本挖掘 API 从文本文件中分离出有意义的词

wpf - 更新标题 : Why ICommand. CanExecute 一直被调用,而不是像事件一样工作?

css 位置 jquery ui 组合框

c# - 绑定(bind)DataSource时如何防止selectedindexchanged事件?