簡體   English   中英

將命令綁定到WPF中的ComboBoxItem

[英]Binding Commands to ComboBoxItem in 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的DataSource,綁定為DataTemplate。

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

我已經對此進行了廣泛的研究,但是沒有找到如何有效地將ICommand綁定到ComboBoxItem的答案。

我正在從使用一組radiobuttons和相關命令的現有代碼中進行調整,這很容易完成。 使用ComboBox沒有簡單的方法嗎?

謝謝。

您是否嘗試將命令置於綁定中?

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

編輯更新策略:

由於ComboBox項不支持直接命令綁定,請嘗試創建附加屬性:

鏈接

我正在查看我的舊帖子,並意識到我從未在我的問題上發布解決方案......非常簡單(如果不是優雅的話)。 我剛剛在我的ViewModel中創建了一個List,其中包含我的Combo Box“選項”,然后當SelectedValue被更改時,觸發了我在屬性的setter中的“更改”邏輯:

<WrapPanel Grid.Row="0" Visibility="{Binding ShowToggleFeedViewManual}" >
    <ComboBox Margin="10,10,10,10" Width="200" ItemsSource="{Binding AvailableDataSources}" SelectedValue="{Binding SelectedDataSource}"/>
</WrapPanel>

從視圖模型:

public FeedSource SelectedDataSource
    {
        get { return _selectedDataSource; }
        set
        {
            _selectedDataSource = value;
            base.OnPropertyChanged("SelectedDataSource");

            //additional code to perform here

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM