C# 在WPF中的UserControl内的控件上显示验证错误模板
如何使WPF错误模板出现在WPF中UserControl内的控件上 我有一个UserControl,它包含两个标签、两个文本框和一个复选框。其中一个文本框表示实体的名称,它绑定到由我的ViewModel(我的窗口的DataContext)公开的模型属性之外的name属性。Model类实现IDataErrorInfo接口,我通过单元测试确认,当名称为空时,通过属性索引器实现返回错误。我已绑定到支持UserControl中的Name TextBox的Dependency属性,当遇到验证错误时,WPF错误模板会在整个UserControl而不仅仅是Name TextBox周围放置一个红色边框 与UserControl的name字段的绑定如下所示C# 在WPF中的UserControl内的控件上显示验证错误模板,c#,wpf,validation,mvvm,idataerrorinfo,C#,Wpf,Validation,Mvvm,Idataerrorinfo,如何使WPF错误模板出现在WPF中UserControl内的控件上 我有一个UserControl,它包含两个标签、两个文本框和一个复选框。其中一个文本框表示实体的名称,它绑定到由我的ViewModel(我的窗口的DataContext)公开的模型属性之外的name属性。Model类实现IDataErrorInfo接口,我通过单元测试确认,当名称为空时,通过属性索引器实现返回错误。我已绑定到支持UserControl中的Name TextBox的Dependency属性,当遇到验证错误时,WPF
my UserControl和backing DependencyProperty的类似版本如下所示
公共部分类MyUserControl:UserControl
{
公共静态只读DependencyProperty ItemNameProperty=
从属属性。寄存器(
“项目名称”,
类型(字符串),
类型(MyUserControl),
新的FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
公共字符串ItemName
{
获取{return(string)GetValue(ItemNameProperty);}
set{SetValue(ItemNameProperty,value);}
}
}
到目前为止,我发现与此问题相关的信息都与Silverlight有关,或者使用转换器不显示红色边框(这对我来说没有意义)。这些信息都是在stackoverflow上找到的
有人能用WPF解决这个问题吗?我是否忽略了一些明显的东西?如果绑定到您的
用户控件
使用,将使用用户控件
的错误模板。但您可以使用删除红色边框
UserControl
中的所有控件只有在通过实现支持依赖属性来验证其绑定时才会显示红色边框
public class MyUserControl : UserControl, IDataErrorInfo
{
public static readonly DependencyProperty ItemNameProperty =
DependencyProperty.Register(
"ItemName",
typeof(string),
typeof(MyUserControl),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
public string ItemName
{
get { return (string)GetValue(ItemNameProperty); }
set { SetValue(ItemNameProperty, value); }
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
// use a specific validation or ask for UserControl Validation Error
return Validation.GetHasError(this) ? "UserControl has Error" : null;
}
}
}
这里是简化的XAML
<UserControl Validation.ErrorTemplate="{x:Null}">
<Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
<TextBox Text="{Binding ItemName, ValidatesOnDataErrors=True}" />
</Grid>
</UserControl>
相关问题和感谢,LPL。我在研究这个问题的过程中看到了这两个问题。关于第二个链接的公认答案是使用我在问题中引用的转换器。这在我看来是大错特错的。第一个问题中被接受的答案似乎对我也不起作用。再次感谢LPL。我最初尝试过类似的更改,但无法确定UserControl内部的哪个文本框有错误,因为调用Validation.GetHasError时文本框本身总是返回false。在我的UserControl中有两个文本框,是否可以确定哪个框实际有错误?不确定我之前做错了什么,但这似乎对我有用。我仍然不知道如何区分唯一文本框上的错误,但在这一点上,我将只对其中一个进行验证。谢谢,LPL!我已经添加了一个建议,以区分这一点上的错误。;)
BindingExpression be = BindingOperations.GetBindingExpression(this, ItemNameProperty);
return be != null && be.HasError ? "ItemName has Error" : null;