2012-07-23 123 views
5

我有一個簡單的ComboBox,每當選定的值更改時,我都要觸發單獨的命令。這裏是我的標記的一個例子:我得到一個錯誤,指出「無法將‘SelectViewFeedDataCommand’將命令綁定到WPF中的ComboBoxItem

<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> 

。我也遇到了另一個ComboBoxItem類似的錯誤。 ICommand在ViewModel類中定義,它是UserControl的DataSource,綁定爲DataTemplate。

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

我研究這個很廣泛,但還沒有找到如何ICommand的有效結合ComboBoxItem答案。

我正在適應從現有的代碼,使用一組radiobuttons和相關的命令,這是很容易做到這一點。有沒有簡單的方法來使用ComboBox做到這一點?

謝謝。

+1

如何將'ComboBox.SelectedItem'屬性綁定到某個對象,然後在SelectedComboBoxItem屬性的PropertyChanged事件中執行命令邏輯? – Rachel 2012-07-23 18:49:49

回答

0

我一直在尋找我的舊文章並意識到我從未將解決方案發布到我的問題上......非常簡單(如果不是很優雅的話)。我只是在我的視圖模型包含我的組合框「選項」,然後在的SelectedValue改爲創建的列表,觸發了我的「改變」的邏輯在二傳手的財產:

<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 

     } 
    } 
0

你有沒有嘗試把命令綁定?

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

編輯的更新策略:

由於ComboBox項不支持直接命令結合,嘗試創建一個附加屬性:

Link

+0

是的,我有。我收到一條錯誤消息:「'Binding'不能在'CommandBinding'類型的'Command'屬性上設置。'Binding'只能在DependencyObject的DependencyProperty上設置。 – jpaull 2012-07-23 15:19:52