Combobox绑定WPF

时间:2016-12-22 14:02:17

标签: c# wpf xaml combobox

我正在尝试在WPF中绑定组合框。这是我的xaml:

<ComboBox x:Name="cmbRptType" HorizontalAlignment="Left" Margin="10,10,0,0" ItemsSource="{Binding Path=ReportTypes}" SelectedValuePath="Type" DisplayMemberPath="Name" VerticalAlignment="Top" Width="198">

        </ComboBox>

这是我背后的代码:

public ObservableCollection<ReportType> ReportTypes = new ObservableCollection<ReportType>()
        {
            new ReportType() { Name = "Store", Type = REPORT_TYPE.STORE },
            new ReportType() { Name = "Customer", Type = REPORT_TYPE.CUSTOMERS }
        };

并在我设置的构造函数中:

DataContext = this;

但我的物品没有出现。还有什么我需要做的吗?

2 个答案:

答案 0 :(得分:1)

请注意,在下面的代码中,不使用_reportTypes而是使用ReportTypes会导致永久循环,因为它会永久更新自己。

private ObservableCollection<ReportType> _reportTypes
public ObservableCollection<ReportType> ReportTypes
  {
     get{return _reportTypes;}
     set
     {
        _reportTypes = value;
        NotifyPropertyChanged(m => m.ReportTypes);
     }
  }

你忘了设置getter,ObservableCollection的设置器,getter和setter在使用绑定时非常重要。

setter获取你传递它的“值”并设置变量的值。

getter等待被调用,当被调用时,它将变量值返回给调用它的项。

Combobox属性

 ItemsSource="{Binding ReportTypes,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"

设置模式和UpdateTrigger也很重要

通过该模式,您可以设置组合框与绑定的交互方式。

使用UpdateSourceTrigger,您可以告诉组合框等待绑定到的项目进行更新,然后它会询问获取者是否有更新的数据

答案 1 :(得分:1)

如果您的组合框项目只是一个固定列表,那么您不需要可观察的集合来实现绑定。如果您要修改ReportTypes并希望这些更改反映在组合框中,那么您需要使用可观察的集合。

public enum REPORT_TYPE
{
    STORE,
    CUSTOMERS
}

public class ReportType
{
    public string Name { get; set; }
    public REPORT_TYPE Type { get; set; }
}

public List<ReportType> ReportTypes { get; set; } = new List<ReportType>()
{
    new ReportType() { Name = "Store", Type = REPORT_TYPE.STORE },
    new ReportType() { Name = "Customer", Type = REPORT_TYPE.CUSTOMERS }
};