wpf绑定自定义isselected属性



我想将属性为"ID"、"Description"one_answers"IsSelected"的项目列表绑定到一个组合框。使用DisplayMemberPath将显示值设置为"Description",效果良好。但是,我希望在选择该项时设置"IsSelected"属性。我尝试过将SelectedValuePath和SelectedValue设置为"IsSelected",但不起作用。

没有什么比重新回答一个五年前的问题更好的了。。。我不同意Mike的观点,因为您应该跟踪这两种状态,因为组合框可以为您提供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>

主窗口视图模型

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

最简单的解决方案可能是在视图模型中跟踪所选项目,并通过向SelectedItem添加双向绑定来保持它与ComboBox同步。当视图模型特性更改时,更新新选择和先前选择的IsSelected特性。

试试这个

    <ComboBox Width="120" Height="35">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <ComboBoxItem IsSelected="{Binding IsSelected}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

相关内容

  • 没有找到相关文章

最新更新