views:

30

answers:

1

I'm still learning the WPF ropes, so if the following question is trivial or my approach wrong-headed, please do speak up... I'm trying to reduce boilerplate and it sounds like styles are a common way to do so. In particular:

I've got a bunch of fairly mundane data-entry fields. The controls for these fields have various properties I'd like to set based on the target of the binding - pretty normal stuff. However, I'd also like to set properties of the binding itself in the style to avoid repetitiveness.

For example:

<TextBox Style="{StaticResource myStyle}">
    <TextBox.Text>
        <Binding Path="..." Source="..."
                 ValidatesOnDataErrors="True"
                 ValidatesOnExceptions="True"
                 UpdateSourceTrigger="PropertyChanged">
        </Binding>
    </TextBox.Text>
</TextBox>

Now, is there any way to use styling - or some other technique to write the previous example somewhat like this:

<TextBox Style="{StaticResource myStyle}" Text="{Binding Source=... Path=...}/>

That is, is there any way to set all bindings that match a particular selection (here, on controls with the myStyle style) to validate data and to use a particular update trigger? Is it possible to template or style bindings themselves?

Alternatively, is it possible to add the binding in the style itself?

Clearly, the second syntax is much, much shorter and more readable, and I'd love to be able to get rid of other similar boilerplate to keep my UI code comprehensible to myself :-).

+1  A: 

You simply cannot use styles to change properties on a Binding. What you can do instead is use the following form to make things prettier:

<TextBox Style="{StaticResource myStyle}"
         Text="{Binding SomePath,Source=SomeSource,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" />

One other thing you can do is derive a class from Binding and use that as a custom markup extension. In your derived class constructor you can set all the common defaults like PropertyChanged for UpdateSourceTrigger, etc.

wpfwannabe