UserControl内的控件上的ValidationRules

时间:2012-08-26 11:08:30

标签: wpf user-controls validationrules

编辑:找到适用于我的解决方案: http://social.msdn.microsoft.com/Forums/en/wpf/thread/c1fd21b2-424b-4536-be8c-335cee94596a

如下:

    private void TextBoxLoaded(object sender, RoutedEventArgs e)
    {
        Binding bd = new Binding(TextBoxText.ToString());
        bd.ValidationRules.Add(new DataErrorValidationRule());
        bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        TextBox tb = sender as TextBox;
        tb.SetBinding(TextBox.TextProperty, bd);
    }

<UserControl x:Class="WpfApplication1.UserControl1"
         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"
         xmlns:wa="clr-namespace:WpfApplication1"
         mc:Ignorable="d">
<DockPanel
    VerticalAlignment="Center">
    <Label
        VerticalAlignment="Center"
        Content="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type wa:UserControl1}},Path=LabelContent}"/>
    <TextBox
        VerticalAlignment="Center"
        MinWidth="96"
        Loaded="TextBoxLoaded">
    </TextBox>
</DockPanel>

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wa="clr-namespace:WpfApplication1"
    Title="MainWindow">
<Window.Resources>
    <DataTemplate x:Key="personDisplay">
        <DockPanel>
            <wa:UserControl1 LabelContent="First name:" TextBoxText="fname"/>
            <wa:UserControl1 LabelContent="Last name:" TextBoxText="lname"/>
            <wa:UserControl1 LabelContent="Age:" TextBoxText="age"/>
        </DockPanel>
    </DataTemplate>
</Window.Resources>
<ContentControl
    VerticalAlignment="Center"
    Name="personCcl"
    ContentTemplate="{StaticResource personDisplay}"/>

END

我有一个需要包含标签和文本框的usercontrol,文本框中的条目需要有一个验证规则来检查输入的值是否有效。我有一个datatemplate,显示一个使用usercontrol具有多个字段的类。该类实现了IDataErrorInfo。但是,我遇到的问题是文本框没有访问类IDataErrorInfo,另外,围绕无效控件的红色轮廓围绕整个用户控件,而不仅仅是用户控件内的文本框。

我已经创建了一个更简单的示例,说明了我在下面尝试做的事情。

这是班级

public class Person : IDataErrorInfo
{
    public string fname { get; set; }
    public string lname { get; set; }
    public int age { get; set; }

    public Person(string f, string l, int a)
    {
        fname = f;
        lname = l;
        age = a;
    }
    public string Error
    {
        get
        {
            if (age < 18) return "Too young";
            else if (fname == null || fname.Length == 0) return "Needs first name";
            else if (lname == null || lname.Length == 0) return "Needs last name";
            return null;
        }
    }
    public string this[string name]
    {
        get
        {
            if (name == "age") { return age < 18 ? "Too young" : null; }
            else if (name == "fname") { return fname == null || fname.Length == 0 ? "Needs first name" : null ; }
            else if (name == "lname") { return lname == null || lname.Length == 0 ? "Needs last name" : null; }
            return null;
        }
    }
}

这是usercontrol:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }
    static readonly public DependencyProperty LabelContentProperty = DependencyProperty.Register(
        "LabelContent",
        typeof(string),
        typeof(UserControl1),
        new FrameworkPropertyMetadata("")
    );
    public string LabelContent
    {
        get { return GetValue(LabelContentProperty) as string; }
        set { SetValue(LabelContentProperty, value); }
    }
    static readonly public DependencyProperty TextBoxTextProperty = DependencyProperty.Register(
        "TextBoxText",
        typeof(object),
        typeof(UserControl1),
        new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnTextBoxTextChanged), new CoerceValueCallback(CoerceTextBoxText))
    );
    public object TextBoxText
    {
        get { return GetValue(TextBoxTextProperty); }
        set { SetValue(TextBoxTextProperty, value); }
    }
    static private void OnTextBoxTextChanged(DependencyObject dob, DependencyPropertyChangedEventArgs ea)
    {
        var uc = dob as UserControl1;
        uc.OnTextBoxTextChanged(new RoutedPropertyChangedEventArgs<object>(ea.OldValue, ea.NewValue, TextBoxTextChangedEvent));
    }
    static private object CoerceTextBoxText(DependencyObject dob, object o)
    {
        return o;
    }
    static readonly public RoutedEvent TextBoxTextChangedEvent = EventManager.RegisterRoutedEvent(
        "TextBoxTextChanged",
        RoutingStrategy.Bubble,
        typeof(RoutedPropertyChangedEventArgs<object>),
        typeof(UserControl1));
    public event RoutedPropertyChangedEventHandler<object> TextBoxTextChanged
    {
        add { AddHandler(TextBoxTextChangedEvent, value); }
        remove { RemoveHandler(TextBoxTextChangedEvent, value); }
    }
    protected virtual void OnTextBoxTextChanged(RoutedPropertyChangedEventArgs<object> ea) { RaiseEvent(ea); }
}

这是usercontrol xaml:

<UserControl x:Class="WpfApplication1.UserControl1"
         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"
         xmlns:wa="clr-namespace:WpfApplication1"
         mc:Ignorable="d">
<DockPanel>
    <Label
        VerticalAlignment="Center"
        Content="{Binding RelativeSource={RelativeSource FindAncestor,
            AncestorType={x:Type wa:UserControl1}},
        Path=LabelContent}"/>
    <TextBox
        VerticalAlignment="Center"
        MinWidth="96">
        <TextBox.Text>
            <Binding 
                    RelativeSource="{RelativeSource FindAncestor,
                        AncestorType={x:Type wa:UserControl1}}"
                    Path="TextBoxText"
                    Mode="TwoWay"
                    UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</DockPanel>

这是窗口xaml(已更新):

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wa="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate x:Key="personDisplay">
        <DockPanel>
            <wa:UserControl1 LabelContent="First name:" TextBoxText="{Binding fname,Mode=TwoWay}"/>
            <wa:UserControl1 LabelContent="Last name:" TextBoxText="{Binding lname,Mode=TwoWay}"/>
            <wa:UserControl1 LabelContent="Age:" TextBoxText="{Binding age,Mode=TwoWay}"/>
        </DockPanel>
    </DataTemplate>
</Window.Resources>
<ContentControl
    VerticalAlignment="Center"
    Name="personCcl"
    ContentTemplate="{StaticResource personDisplay}"/>
</Window>

这是Window构造函数

    public MainWindow()
{
  InitializeComponent();
  personCcl.Content = new Person("John", "Smith", 33);
}

1 个答案:

答案 0 :(得分:1)

那是错的。不要制作personCc1.Content = new Person。使其成为personCc1.DataContext = new Person。内容期望您只显示该类的值,主要用于UI。