ComboBox SelectedItem绑定

时间:2019-06-28 13:35:26

标签: c# wpf xaml mvvm observablecollection

我的视图中有一个组合框:

<ComboBox Name="comboBox1" ItemsSource="{Binding MandantList}" SelectedItem="{Binding CurrentMandant, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Firma}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

这是我的模型

public class MandantListItem : INotifyPropertyChanged
{
    public MandantListItem() { }

    string _Firma;
    bool _IsChecked;

    public string Firma
    {
        get { return _Firma; }
        set { _Firma = value; }
    }
    public bool IsChecked
    {
        get
        {
            return _IsChecked;
        }
        set
        {
            _IsChecked = value;
            OnPropertyChanged(nameof(IsChecked));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

这是我的 ViewModel

public class MaViewModel : INotifyPropertyChanged
{
    public ObservableCollection<MandantListItem> MandantList { get { return _MandantList; } }
    public ObservableCollection<MandantListItem> _MandantList = new ObservableCollection<MandantListItem>();

    private MandantListItem _CurrentMandant;
    public MandantListItem CurrentMandant
    {
        get { return _CurrentMandant; }
        set
        {
            if (value != _CurrentMandant)
            {
                _CurrentMandant = value;
                OnPropertyChanged("CurrentMandant");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

如何填充组合框:

public zTiredV2.ViewModel.MaViewModel MAList = new zTiredV2.ViewModel.MaViewModel();
this.comboBox1.ItemsSource = MAList.MandantList;
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "A", Homepage = "a.com", IsChecked = false });
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "B", Homepage = "b.com", IsChecked = false });

但是我的项目没有更新...也通过IsChecked尝试过,但是也没有成功...当我通过MAList进行迭代时,IsChecked始终为false。以及如何将TextBlock绑定到所选的Firma?

使用MVVM很难,但我喜欢它。

1 个答案:

答案 0 :(得分:1)

您应将DataContext中的ComboBox设置为视图模型的实例。否则绑定将无法工作:

this.comboBox1.DataContext = MAList;

还请注意,您的媒体资源的_MandantList支持字段不应公开。实际上,您根本不需要它:

public ObservableCollection<MandantListItem> MandantList { get; } = new ObservableCollection<MandantListItem>();

DataContext中选择一个项目时,设置CurrentMandant应该会导致ComboBox属性被设置。但是,它不会设置IsChecked属性。