Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto WPF Binding written inline = short form

Tags:

binding

wpf

I have about 100 TextBoxes in a Form. I need to validate them if they are decimal for instance. This works, but it is too verbose, I don't want to have 800 in place of 100 rows in XAML.

<TextBox.Text>
    <Binding Path="MyPath" UpdateSourceTrigger="PropertyChanged" Stringformat="{}{0:N}" NotifyOnValidationError="True">
        <Binding.ValidationRules>
            <myRulesNamespace:MyValidationRule ValidationType="decimal" />
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

Is there any way how to rewrite it to the short form like this? :

Text="{Binding MyPath, UpdateSourceTrigger='PropertyChanged', StringFormat='{}{0:N}', NotifyOnValidationError=True, ValidationRules NOW WHAT?}"
like image 217
theSpyCry Avatar asked Jun 29 '10 13:06

theSpyCry


2 Answers

Short answer: You cannot. The Validation-rules property is a collection, and there is currently no way to write these in the Binding shorthand.

You can however create a class inheriting from Binding, like this:

public class SuperBinding:Binding
{
    public SuperBinding()
    {
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        ValidationRules.Add(new MyValidationRule{ValidationType = typeof(decimal)});
        //set rest of properties
    }
}

And then use that instead of the normal Binding tag.

like image 158
Goblin Avatar answered Nov 01 '22 16:11

Goblin


If you contained your 100 TextBoxes in a list container control, such as a ListBox or ListView, you could put this binding into a DataTemplate. Then the validation rule would be applied to each item.

Since it's possible to re-template any container control, you would still be able to get the layout you want.

like image 26
Rob Perkins Avatar answered Nov 01 '22 16:11

Rob Perkins