【发布时间】:2017-01-06 18:45:42
【问题描述】:
我正在尝试用列表填充 wpf 组合框。我有两个问题。
- 它不填充任何内容
- 我正在使用数据注释进行验证。它没有在错误显示区域设置“必需”错误消息。
这是我的组合框 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"/>
这是我声明和填充我的 States 对象的部分视图模型。
ViewModel 中的属性
public ObservableCollection<string> States;
构造函数:
States = new ObservableCollection<string>();
States.Add("One");
States.Add("Two");
States.Add("Three");
States.Add("Four");
States.Add("Five");
这是来自我的 Debug 的证明,证明我正在正确地获取视图的状态。
它适用于其他领域,没有任何问题,如下所示:
【问题讨论】:
-
ViewModel 中的属性
public ObservableCollection<string> States;-- 这不是属性。这是一个领域。你不能绑定它。您只能绑定到属性。您需要通过给它{ get; set; }使其成为一个属性。其次,您“将状态正确地放入视图”的“证明”对我来说没有任何意义;你说“查看”是什么意思? -
请注意,在 ItemsSource 绑定上设置
UpdateSourceTrigger=PropertyChanged和Mode=TwoWay是没有意义的,因为绑定永远不会更新源。