簡體   English   中英

ComboBox SelectedItem 綁定

[英]ComboBox SelectedItem Binding

我的視圖中有一個 ComboBox :

<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 很難,但我喜歡它。

您應該將ComboBoxDataContext設置為您的視圖模型的實例。 否則綁定將不起作用:

this.comboBox1.DataContext = MAList;

另請注意,您的資產的_MandantList支持字段不應公開。 事實上,你根本不需要它:

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

當您在ComboBox選擇一個項目時,設置DataContext應該會導致設置CurrentMandant屬性。 但是它不會設置IsChecked屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM