如何在字符串索引器数据绑定上实现 IDataErrorInfo?
使用 xaml(注意字典条目属性 [Welcome] 上的绑定):
<Grid x:Name="LayoutRoot"> <StackPanel> <TextBlock FontSize="36" FontWeight="Bold" Foreground="Purple" Text="{Binding Attributes[Welcome]}" VerticalAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap" /> <TextBox Text="{Binding Attributes[Welcome],Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox> <TextBox Text="{Binding Attributes[Welcome],Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox> <TextBox Text="{Binding Test, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox> <TextBox Text="{Binding Test, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox> </StackPanel> </Grid>When the view model implements IDataErrorInfo as:
public string Error
{
get { return ""; }
}
public string this[string columnName]
{
get {
return "Compulsory Error";
}
}
只有 columnName == "Test" 才能通过。因此我得到了以下申请:
如何验证为属性字典设置的值?
With xaml (notice the binding on dictionary entry Attributes[Welcome]):
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBlock FontSize="36"
FontWeight="Bold"
Foreground="Purple"
Text="{Binding Attributes[Welcome]}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap" />
<TextBox Text="{Binding Attributes[Welcome],Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
<TextBox Text="{Binding Attributes[Welcome],Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
<TextBox Text="{Binding Test, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
<TextBox Text="{Binding Test, Mode=TwoWay, ValidatesOnDataErrors=True}"></TextBox>
</StackPanel>
</Grid>
When the view model implements IDataErrorInfo as:
public string Error
{
get { return ""; }
}
public string this[string columnName]
{
get {
return "Compulsory Error";
}
}
Only columnName == "Test" is ever passed. And therefore I get the following application:
How can I validate the values being set for the Attributes Dictionary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为我需要在字典上实现 IDataErrorInfo 而不是包含字典的视图模型。但由于 IDataErrorInfo 成员与 IDicitonary 冲突。我最终实现了 INotifyDataErrorInfo。
I figured that I needed to implement IDataErrorInfo on the Dictionary rather than the viewmodel containing the dictionary. But since IDataErrorInfo member's conflict with IDicitonary. I ended up implementing INotifyDataErrorInfo.
不使用字典,更“MVVMish”的方法是为要在列表中显示的项目创建一个简单的 ViewModel。然后将它们添加到列表(而不是字典)中并绑定到这些项目。然后,您可以在这些 ViewModel 上实现 IDataErrorInfo(以及任何其他自定义逻辑或您需要的任何其他内容)。
Instead of using a Dictionary the more "MVVMish" way would be to create a simple ViewModel for the items you are going to display in your list. Then add them to a list (instead of a dictionary) and bind to those items. Then you can implement IDataErrorInfo on those ViewModels (along with any other custom logic or anything else you need).