我想要一个<ComboBox>
,其中ItemsSource绑定到某些 ViewModel 集合,但我希望第一个<ComboBoxItem>
绑定到ICommand
属性,并命名(例如)&#34; 将新元素添加到集合中...... &#34;。
有什么建议?
答案 0 :(得分:4)
你可以这样做:
在您的视图模型中,您要将Command
和Items
集合设置为ItemsSource
:
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));
}
}
您在XAML中使用CompositeCollection
添加&#34;添加新项目&#34;在你的收藏品前面:
<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
以禁止选择第一个项目,即&#34;添加新项目&#34;项:
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();
}
}
结果: