带有MVVM和DataAnnotations的WPF,UserControl中的验证错误

时间:2013-10-07 01:09:17

标签: c# wpf validation mvvm

我有一个UserControl,将在我们正在开发的应用程序中重用。 我们正在使用基于MVVMLight的框架。

为简单起见,假设用户控件只包含一个文本框,并公开一个名为“Quantity”的依赖项属性。用户控件上的文本框数据绑定到依赖项属性“Quantity”。

在视图上使用用户控件时,usercontrol的“Quantity”依赖项属性将数据绑定到ViewModel中的属性。 (此ViewModel是我们通过MVVMLight ViewModelLocator查看的datacontext。)

这一切都很棒!绑定工作,属性设置像我期望的那样。一切都很好,直到验证。

我们正在使用DataAnnotations来装饰我们的ViewModel属性。 ViewModel包含INotifyDataErrorInfo的自定义实现。我们为大多数输入控件实现了自定义样式,以在控件周围显示红色边框,并在控件旁边显示一条消息,显示验证错误消息。所有这些在正常情况下都很有效(例如,View上的文本框绑定到视图模型中的属性)。

当我尝试使用此用户控件的相同方法时,我最终得到的是整个用户控件周围的红色边框,并且实际文本框上没有错误指示。似乎存在错误的事实正在UI中反映出来,但它只是没有达到我想要它的控制。

我已经在stackoverflow上搜索了这个问题,对于那些带有解决方案的问题,似乎没有一个适用于我的情况。

我的第一个猜测是因为实际的文本框直接绑定到依赖项属性本身而不是我的视图模型上的属性,因此没有正确通知生成的错误。有没有办法通过usercontrol传播视图模型中生成的错误,然后再传递到文本框?

你能给予的任何帮助或建议都会很棒,谢谢。

这是UserControl xaml。

<UserControl x:Class="SampleProject.UserControls.SampleControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"  x:Name="sampleControl"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=sampleControl}">
        <TextBox Text="{Binding Path=Quantity, ValidatesOnDataErrors=True}" Width="100" Height="30" />
</Grid>
</UserControl>

后面的UserControl代码。

public partial class SampleControl : UserControl
{
    public SampleControl()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty QuantityProperty = 
         DependencyProperty.Register("Quantity", typeof(int?), typeof(SampleControl), 
    new FrameworkPropertyMetadata{DefaultValue=null, BindsTwoWayByDefault = true});

    public int? Quantity
    {
        get { return (int?)GetValue(QuantityProperty); }
        set { SetValue(QuantityProperty, value); }
    }
}

用于视图。

<userControls:SampleControl Grid.Row="1" Quantity="{Binding Path=Quantity, ValidatesOnDataErrors=True}" Height="60" Width="300"/>

ViewModel属性。

[Required(ErrorMessage = "Is Required")]
[Range(5, 10, ErrorMessage = "Must be greater than 5")]
public int? Quantity
{
    get { return _quantity; }
    set { Set(() => Quantity, ref _quantity, value); }
}
private int? _quantity;

(*注意,setter中的Set方法只是基本视图模型中的一个辅助方法,用于设置支持属性并为其引发PropertyChanged事件。)

2 个答案:

答案 0 :(得分:0)

尝试从DataContext中删除UserControl。而不是使用Bind TextBoxRelativeSource直接从Binding设置为实际属性:

<TextBox Text="{Binding Quantity, RelativeSource={RelativeSource Mode=FindAncestor, 
    AncestorType={x:Type YourControlNamespace:SampleControl, 
    ValidatesOnDataErrors=True}}}" Width="100" Height="30" />

更新&gt;&gt;&gt;

如果失败,只要绑定到此属性的视图模型始终具有要绑定的同名属性,就可以使Binding进行搜索父母'DataContext是这样的:

<TextBox Text="{Binding Quantity, RelativeSource={RelativeSource Mode=FindAncestor, 
    AncestorLevel=2, ValidatesOnDataErrors=True}}}" Width="100" Height="30" />

您需要将2更改为TextBox在到达具有正确属性访问权限的控件之前具有的正确元素数。例如,使用2级别意味着框架将尝试在Quantity的{​​{1}}中找到名为BindDataContext的属性父母的父母控制。 更难以使用TextBox,因为我认为像AncestorLevel这样的'隐藏'元素不包含在父母中。

答案 1 :(得分:0)

您需要拾取在usercontrol上设置的绑定并将其放置在控件上,而无需将usercontrol绑定到它自己的DataContext。 可以在加载用户控件后完成。

为防止用户控件周围出现红色边框,请删除默认错误模板:

Validation.ErrorTemplate="{x:Null}"

示例用户控件XAML:

UserControl x:Class="DxUserControlValidation.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         Validation.ErrorTemplate="{x:Null}"
         d:DesignHeight="450" d:DesignWidth="800">
<StackPanel Orientation="Vertical">
    <TextBlock Text="Value 1:" Margin="2"/>
    <TextBox Name="txtBox1" Margin="2"/>
    <TextBlock Text="Value 2:" Margin="2"/>
    <TextBox Name="txtBox2" Margin="2"/>
</StackPanel>

public partial class MyUserControl : UserControl
{
    public static readonly DependencyProperty Value1Property;
    public static readonly DependencyProperty Value2Property;

    static MyUserControl()
    {
        Value1Property = DependencyProperty.Register("Value1", typeof(string), typeof(MyUserControl), new FrameworkPropertyMetadata { DefaultValue = null, BindsTwoWayByDefault = true });
        Value2Property = DependencyProperty.Register("Value2", typeof(string), typeof(MyUserControl), new FrameworkPropertyMetadata { DefaultValue = null, BindsTwoWayByDefault = true });
    }

    public MyUserControl()
    {
        InitializeComponent();

        Loaded += (s, e) =>
        { 
            Binding value1Binding = BindingOperations.GetBinding(this, Value1Property);
            if (value1Binding != null) txtBox1.SetBinding(TextBox.TextProperty, value1Binding);
            Binding value2Binding = BindingOperations.GetBinding(this, Value2Property);
            if (value2Binding != null) txtBox2.SetBinding(TextBox.TextProperty, value2Binding);
        };
    }

    public string Value1
    {
        get { return (string)GetValue(Value1Property); }
        set { SetValue(Value1Property, value); }
    }

    public string Value2
    {
        get { return (string)GetValue(Value2Property); }
        set { SetValue(Value2Property, value); }
    }
}

如果没有绑定,则可以将值直接分配给控件:

if (value2Binding != null) txtBox2.SetBinding(TextBox.TextProperty, value2Binding);
else txtBox2.Text = Value2;
相关问题