2016-02-05 168 views
0

我想有一個<ComboBox>,其ItemsSource綁定到一些視圖模型集合,但我希望第一個<ComboBoxItem>綁定到ICommand財產,並將其命名爲(例如)「新元素添加到集合.. 。「」。 有什麼建議嗎?將ComboBoxItem綁定到WPF中的命令?

回答

4

你可以這樣做:

在您的視圖模型,你必須要設置爲ItemsSourceCommandItems集合:

public class MainWindowViewModel : INotifyPropertyChanged 
{ 
    public MainWindowViewModel() 
    { 
     Items = new ObservableCollection<string>() 
     { 
      "John Doe", 
      "Lara Croft", 
      "Sam Fisher" 
     }; 

     AddNewItemCommand = new DelegateCommand(OnAddNewItem); 
    } 

    private void OnAddNewItem() 
    { 
     Items.Add("New Item"); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private ObservableCollection<string> _items; 
    public ObservableCollection<string> Items 
    { 
     get { return _items; } 
     set 
     { 
      _items = value; 
      NotifyPropertyChanged(nameof(Items)); 
     } 
    } 

    public ICommand AddNewItemCommand { get; set; } 

    [NotifyPropertyChangedInvocator] 
    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

您使用CompositeCollection在XAML添加「添加新項目」在您的集合前:

<ComboBox> 
    <ComboBox.Resources> 
     <CollectionViewSource x:Key="ItemsCollection" Source="{Binding Path=Items}" /> 
    </ComboBox.Resources> 
    <ComboBox.ItemsSource> 
     <CompositeCollection> 
      <ComboBoxItem FontStyle="Italic"> 
       <i:Interaction.Behaviors> 
        <local:UnselectableComboBoxItemBehavior /> 
       </i:Interaction.Behaviors> 
       <TextBlock> 
       <Hyperlink Command="{Binding AddNewItemCommand}">Add new item</Hyperlink> 
       </TextBlock> 
      </ComboBoxItem> 
      <CollectionContainer Collection="{Binding Source={StaticResource ItemsCollection}}" /> 
     </CompositeCollection> 
    </ComboBox.ItemsSource> 
</ComboBox> 

並創建一個Behavior要抑制的是 「添加新項」 項目的第一項選擇:

public class UnselectableComboBoxItemBehavior : Behavior<ComboBoxItem> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 
     AssociatedObject.PreviewMouseDown += AssociatedObjectOnPreviewMouseDownAndMouseLeftButtonUp; 
     AssociatedObject.PreviewMouseLeftButtonUp += AssociatedObjectOnPreviewMouseDownAndMouseLeftButtonUp; 
    } 

    private void AssociatedObjectOnPreviewMouseDownAndMouseLeftButtonUp(object sender, MouseButtonEventArgs e) 
    { 
     if (e.Source == sender) 
     { 
      e.Handled = true; 
     } 
    } 

    protected override void OnDetaching() 
    { 
     AssociatedObject.PreviewMouseDown -= AssociatedObjectOnPreviewMouseDownAndMouseLeftButtonUp; 
     AssociatedObject.PreviewMouseLeftButtonUp -= AssociatedObjectOnPreviewMouseDownAndMouseLeftButtonUp; 
     base.OnDetaching(); 
    } 
} 

結果:

enter image description here

+0

不錯。但是現在我想知道,是否有可能將它包含到一些可重用的UserControl中? Smth like:? – klutch1991