【问题标题】:Bind Command to a ComboBoxItem in WPF将命令绑定到 WPF 中的 ComboBoxItem
【发布时间】:2018-04-06 07:54:07
【问题描述】:

我有一个带有ComboBox 的 wpf 项目。里面的项目是动态填写的。所以它绑定到一个包含Label 和命令的模型。

如果用户在下拉列表/ComboBox 中选择一个项目,则应执行命令。我用包含TextBlockHyperlink 命令的DataTemplate 进行了尝试。但是该命令只会在选择 Label (Hyperlink) 时执行,而不是在我单击整个项目时执行。

<ComboBox ItemsSource="{Binding Path=States}" SelectedItem="{Binding CurrentState}" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Hyperlink Command="{Binding Command}" TextDecorations="None" Foreground="Black">
                    <TextBlock Text="{Binding Path=Label}"/>
                </Hyperlink>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

所以现在的问题是,如何将我的命令绑定到 ComboBoxItem

【问题讨论】:

    标签: wpf xaml combobox binding command


    【解决方案1】:

    ComboBoxItem 没有 Command 属性,但您可以从 CurrentState 属性的设置器执行命令:

    private State _currentState;
    public State CurrentState
    {
        get { return _currentState; }
        set
        {
            _currentState = value;
            if (_currentState != null)
            {
                _currentState.Command.Execute(null);
            }
        }
    }
    

    每当您在ComboBox 中选择一个项目时,都会设置此属性。另一种选择是处理视图中的SelectionChanged 事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-23
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2014-11-06
      • 1970-01-01
      相关资源
      最近更新 更多