Wpf UserControl内部控件的ValidationRules

Wpf UserControl内部控件的ValidationRules,wpf,user-controls,validationrules,Wpf,User Controls,Validationrules,编辑:在此处找到适合我的解决方案: 详情如下: private void TextBoxLoaded(object sender, RoutedEventArgs e) { Binding bd = new Binding(TextBoxText.ToString()); bd.ValidationRules.Add(new DataErrorValidationRule()); bd.UpdateSourceTrigger =

编辑:在此处找到适合我的解决方案:

详情如下:

    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);
    }


那是错误的。不要把人变成1。内容=新人。设为personCc1.DataContext=新人。Content希望您只显示该类的值,主要用于UI。

如果我错了,请更正我。您希望对文本框进行验证,并将其DataContext设置为ViewModel以启动验证?我不确定你想在这里实现什么我还是wpf新手,所以我不能正确地表达所有的术语。例如,在上面的代码中,在保存年龄值的文本框中,如果我输入15,它应该转到person类并检查验证规则,然后确定这是“太年轻”。但这并没有发生。似乎正在发生的是,文本框的绑定只是一个经过验证的字符串。我希望对person类上的IDataErrorInfo进行验证,但它只应用于特定的文本框,而不是整个用户控件。希望这有助于解释问题。您是否将ContentControl的DataContext设置为个人的类?是的,对不起,在主窗口的构造函数中,我编辑了原始的PostSimular问题和解决方案:啊,好的。有机会我会试试的。谢谢
<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}"/>
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;
        }
    }
}
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 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>
<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>
    public MainWindow()
{
  InitializeComponent();
  personCcl.Content = new Person("John", "Smith", 33);
}