首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UserControl内部控件上的ValidationRules

UserControl内部控件上的ValidationRules
EN

Stack Overflow用户
提问于 2012-08-26 19:08:30
回答 1查看 1.6K关注 0票数 3

编辑:在这里找到一个适合我的解决方案:http://social.msdn.microsoft.com/Forums/en/wpf/thread/c1fd21b2-424b-4536-be8c-335cee94596a

如下所示:

代码语言:javascript
复制
    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);
    }

代码语言:javascript
复制
<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>

代码语言:javascript
复制
<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}"/>

结束

我有一个用户控件,它需要包含一个标签和一个文本框,文本框上的条目需要有一个验证规则来检查输入的值是否有效。我有一个数据模板,它使用用户控件显示一个包含多个字段的类。该类实现了IDataErrorInfo。然而,我遇到的问题是,textbox不能访问类IDataErrorInfo,另外,围绕无效控件的红色轮廓位于整个用户控件周围,而不仅仅是用户控件内的textbox。

我已经创建了一个更简单的例子来说明我下面要做的事情。

这是类

代码语言:javascript
复制
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;
        }
    }
}

下面是用户控件:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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 (更新):

代码语言:javascript
复制
<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>

下面是窗口构造函数

代码语言:javascript
复制
    public MainWindow()
{
  InitializeComponent();
  personCcl.Content = new Person("John", "Smith", 33);
}
EN

回答 1

Stack Overflow用户

发布于 2012-08-27 07:35:29

这是错误的。不要让personCc1.Content = new Person。将其设置为personCc1.DataContext = new Person。Content希望您只显示该类的值,并且主要用于UI。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12129600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档