【问题标题】:Can I set some validation to be a default setting on a TextBox instance?我可以将一些验证设置为 TextBox 实例的默认设置吗?
【发布时间】:2015-02-12 16:09:46
【问题描述】:

在我的程序中,我有很多文本框。

它们都是通过 MVVM-Pattern 绑定的。

一切都很好。现在我想实现某种验证,并决定混合使用验证规则和! IData 错误信息。 在测试了几次之后,一切都很好。 但现在我有一个问题。

我像这样编写 XAML 代码

<TextBox Style="{StaticResource TextBoxStyle}" Width="150" >
    <TextBox.Text>
        <Binding Path="Name" Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged" />
    </TextBox.Text>
</TextBox>

假设我总共有 40 个文本框。我总是要写吗

Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged"

或者我可以将其设置为某种默认值吗?

由于三个属性,我不想创建派生的 TextBox。

【问题讨论】:

    标签: c# wpf validation mvvm


    【解决方案1】:

    首先Textbox.Text默认绑定TwoWay,这里不需要指定。另一方面,我想到的唯一想法是创建一个 CustomBinding。

        public class MyBinding : Binding
    {
        public MyBinding()
            :base()
        {
            this.Mode = BindingMode.TwoWay;
            this.ValidatesOnDataErrors = true;
            this.ValidatesOnExceptions = true;
            this.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
        }
    
        public MyBinding(string path) 
            : base(path)
        {
            this.Mode = BindingMode.TwoWay;
            this.ValidatesOnDataErrors = true;
            this.ValidatesOnExceptions = true;
            this.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
        }
    }
    
    
    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="txt">
            <TextBox.Text>
                <local:MyBinding Path="Value" />
            </TextBox.Text>
        </TextBox>
    </Grid>
    

    【讨论】:

    • 谢谢马丁。我认为这是一个可以接受的解决方案,因为它非常紧凑且可重复使用
    猜你喜欢
    • 2011-04-05
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2012-08-13
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多