Tod
Tod

Reputation: 8232

How to put binding information into a Resource

I was experimenting with using App.Config Properties.Settings in XAML. For instance I added a setting for GridMaxWidth as an int of 500. Then in my XAML I added

<UserControl ...
    xmlns:Properties="clr-namespace:MyMainNamespace.Properties"
    ....>

<SomeControl 
    MaxWidth={Binding Source={x:Static Properties:Settings.Default},
                      Mode="OneWay,
                      Path=GridMaxWidth}">

This works fine. My question is: Is there some way to reduce the visual clutter and put all that binding source and mode information in a resource dictionary? I tried putting a <binding> property in a resource file but the xaml couldn't see it.

Upvotes: 0

Views: 175

Answers (1)

user572559
user572559

Reputation:

Most times Bindings get created for good and not supposed to be customised, so it is safe to create a binding in code:

Example


public class MaxWidthBidning: MultiBinding
{
   public MaxWidthBidning()
   {
      this.Bindings.Add(...)
      ...
   }
}

The approach helps a lot when dealing with bulky MultiBindings with converters, turning 5++ lines of XAML into one.


<local:Control ComplexProperty={local:MaxWidthBidning} />

Update 1 - Talking of reducing the 'visual clutter' in general I can call two principal techniques we use:

  1. For Non Sealed objects, accepted by XAML (note, some derived objects cannot be used in XAML by some reason (exact type match is expected instead of a check for IsDervied) - so always try it out before. An example is Bidning - you can create a class dervied from Binding and hardwire the stuff (individual MultiBinding paths & converter), which is not supposed to be modified in XAML.

  2. For Sealed Objects, for example - DoubleAnimationUsingKeyFrames - you can create an attached behavior, something like 'StreamlinedAnimation.Definition' and using it create bulky parts in code. So, your animation will look like:


<DoubleAnimationUsingKeyFrames local:StreamlinedAnimation.Definiton="Some Encoded information to be used for creating Frames" />

Upvotes: 1

Related Questions