Combobox绑定WPF

我想在WPF中绑定组合框。这是我的XAML:Combobox绑定WPF

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

但我的项目没有显示出来。还有什么我需要做的?

回答:

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

private ObservableCollection<ReportType> _reportTypes 

public ObservableCollection<ReportType> ReportTypes

{

get{return _reportTypes;}

set

{

_reportTypes = value;

NotifyPropertyChanged(m => m.ReportTypes);

}

}

你忘了设置有吸附剂和的ObservableCollection的二传手,使用绑定时getter和setter方法是非常重要的。

setter采用通过它的“值”并设置变量的值。

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

组合框属性

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

设置模式和UpdateTrigger也经由该模式非常重要

可以设置组合框与结合的交互方式。

与UpdateSourceTrigger你可以告诉组合框等它被绑定到要更新的项目,然后它要求getter是否更新数据

回答:

如果你的组合框的项目只将是一个固定列表那么你不需要可观察的集合来实现绑定。如果您要修改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 }

};

以上是 Combobox绑定WPF 的全部内容, 来源链接: utcz.com/qa/266616.html

回到顶部