简体   繁体   English

WPF ComboBox绑定到列表<string>

[英]WPF ComboBox Binding to List<string>

I am trying to populate the wpf combobox with list. 我试图用列表填充wpf组合框。 I have two problems with it. 我有两个问题。

  1. It doesn't populate anything 它不会填充任何东西
  2. I am using Data Annotation for the validation. 我正在使用数据注释进行验证。 It doesn't set "Required" Error message in error display area. 在错误显示区域中未设置“必填”错误消息。

Here is my XAML for the combobox: 这是我的组合框XAML:

<Label Target="{Binding ElementName=State}" Grid.Row="10" Grid.Column="0">State:</Label>
        <ComboBox x:Name="State" Margin="10,0,0,10" Grid.Column="1" Grid.Row="10" ItemsSource="{Binding Path=States, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"  Validation.Error="Validation_Error" SelectedValue="{Binding Path=FamilyMember.State}"/>   
        <TextBlock Grid.Column="2" Grid.Row="10" Style="{StaticResource TextBlockStyle}" Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=State}" Margin="10,0,0,10"/>

Here is my partial viewmodel where I am declaring and populating my States object. 这是我声明和填充“状态”对象的局部视图模型。

Property in ViewModel ViewModel中的属性

public ObservableCollection<string> States;

Constructor: 构造函数:

States = new ObservableCollection<string>();
            States.Add("One");
            States.Add("Two");
            States.Add("Three");
            States.Add("Four");
            States.Add("Five");

Here is the proof from my Debug that I am getting states correctly to a view. 这是来自Debug的证明,表明我可以正确获取视图的状态。 在此处输入图片说明

And another problem is that my data annotation error is not working Here is my partial Model: 另一个问题是我的数据注释错误不起作用这是我的部分模型: 在此处输入图片说明

It is working for other fields without any problems as seen below: 它适用于其他领域,没有任何问题,如下所示:

在此处输入图片说明

Change this field: 更改此字段:

public ObservableCollection<string> States;

to a property: 到物业:

public ObservableCollection<string> States {get; set;}

Binding does not work on fields even if they are public. 即使字段是公共的,绑定也不起作用。

Change the States as full property in your view model and add the display member path in your combo box for your xaml file. 在视图模型中更改“状态为完整”属性,并在组合框中为xaml文件添加显示成员路径。

View Model: 查看模型:

public ObservableCollection<string> _state = new ObservableCollection<string>();
public ObservableCollection<string> States 
{
 get{return _state;}
set {_state = value; OnPropertyChange("States");}
}

If you need more clarification refer this page: https://www.codeproject.com/Articles/301678/Step-by-Step-WPF-Data-Binding-with-Comboboxes 如果您需要更多说明,请参阅以下页面: https : //www.codeproject.com/Articles/301678/Step-by-Step-WPF-Data-Binding-with-Comboboxes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM