我想将具有属性“ID”,“描述”和“IsSelected”的项目列表绑定到组合框。显示值使用DisplayMemberPath设置为“描述”,工作正常。但是我希望在选择该项目时设置'IsSelected'属性。我已经尝试将SelectedValuePath和SelectedValue设置为'IsSelected',但它不起作用。
答案 0 :(得分:0)
最简单的解决方案可能是跟踪视图模型中的所选项目,并通过向ComboBox
添加双向绑定使其与SelectedItem
保持同步。当视图模型属性更改时,更新新选项和先前选择的IsSelected
属性。
答案 1 :(得分:0)
试试这个
<ComboBox Width="120" Height="35">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem IsSelected="{Binding IsSelected}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
答案 2 :(得分:0)
没有什么比重新回答一个已有五年历史的问题了……我不同意 Mike ,因为ComboBox可以为您提供SelectedValue的IsSelected状态,因此您应该跟踪这两个状态。 Matrix 在右边,但是您不能将IsSelected与DisplayMemberPath一起使用。
通过下面的代码,我的Fruits Selected属性绑定到IsSelected。
查看代码
<ComboBox ItemsSource="{Binding Fruit}"
SelectedValue="{Binding SelectedFruitViewModel}"
DisplayMemberPath="Name">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsSelected" Value="{Binding Selected}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
MainWindowViewModel
public class MainWindowViewModel : BaseViewModel
{
private FruitViewModel _selectedFruitViewModel;
public MainWindowViewModel()
{
this.Fruit = new ObservableCollection<FruitViewModel>
{
new FruitViewModel { Name = "Pineapple", Selected = false },
new FruitViewModel { Name = "Apple", Selected = false },
new FruitViewModel { Name = "Orange", Selected = false },
new FruitViewModel { Name = "Kiwi", Selected = false }
};
}
public ObservableCollection<FruitViewModel> Fruit { get; }
public FruitViewModel SelectedFruitViewModel
{
get => _selectedFruitViewModel;
set => SetProperty(ref _selectedFruitViewModel, value);
}
}
FruitViewModel
public class FruitViewModel : BaseViewModel
{
private bool _selected;
private string _name;
public bool Selected
{
get => _selected;
set => SetProperty(ref _selected, value);
}
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
}
BaseViewModel
public class BaseViewModel : INotifyPropertyChanged
{
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T storage,
T value,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
{
return false;
}
storage = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
}