我可以將一些驗證設置為TextBox實例的默認設置嗎? - Can I set some validation to be a default setting on a TextBox instance? -开发者知识库

我可以將一些驗證設置為TextBox實例的默認設置嗎? - Can I set some validation to be a default setting on a TextBox instance? -开发者知识库,第1张

In my program I have lots of Textboxes.

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

They are all bound via MVVM-Pattern.

它們都是通過MVVM-Pattern綁定的。

Everything works nice. Now I want to implent some kind of Validation and have decided to use a mix of Validationrules AND! IDataErrorInfo. After testing this out a few times it all works well. But now I have a question.

一切都很好。現在我想實現某種驗證,並決定使用Validationrules AND的混合! IDataErrorInfo的。經過幾次測試后,一切運行良好。但現在我有一個問題。

I write my XAML-Code like

我寫的XAML-Code就像

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

Lets say I have 40 TextBoxes in total. Do I always have to write

可以說我總共有40個TextBoxes。我總是要寫

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

or can I set this to be some sort of default?

或者我可以將其設置為某種默認值?

I do not want to create a derived TextBox because of three properties.

我不想因為三個屬性而創建派生的TextBox。

1 个解决方案

#1


1  

First of all, Textbox.Text binds TwoWay by default, so no need to specify it here. For the other thing, the only idea that comes to my mind is to create a CustomBinding.

首先,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>

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复