Reputation: 5575
I want to let the user customize the background of of my application and select either a color or an image WITH an opacity binding. I want to do this in XAML if possible.
I seem to be very close - the code below works great with either the color OR the image brush (if I comment out the other), but I cannot figure out a way on how to return the appropriate brush depending on a boolean (UseBackgroundImage).
If you look in the code below you can see I have commented out the ImageBrush - I tried putting in a VisibilityConverter bound to UseBackgroundImage but the Brush object does not use the Visibility property.
I thought about writing a converter to return the appropriate brush but then I can't figure out how to apply the Opacity to just the background (it applies to the all the content).
<navigation:Frame>
<navigation:Frame.Background>
<SolidColorBrush Color="{Binding Config.BackgroundColorInfo.Value}" Opacity="{Binding Config.BackgroundOpacity}" />
<!--<ImageBrush ImageSource="/TourneyManager;component/image.JPG" Stretch="UniformToFill" Opacity="{Binding Config.BackgroundOpacity}"/>-->
</navigation:Frame.Background>
<navigation:Frame.UriMapper>
I then tried setting the bindings in the code behind like this:
SolidColorBrush backgroundBrush = new SolidColorBrush();
Binding b = new Binding("Config.BackgroundColorInfo.Value");
ContentFrame.SetBinding(SolidColorBrush.ColorProperty, b);
Binding b1 = new Binding(".BackgroundOpacity");
ContentFrame.SetBinding(SolidColorBrush.OpacityProperty, b1);
ContentFrame.Background = backgroundBrush;
But the SolidColorBrush class does not have the SetBinding method, so no joy there.
Any suggestions on how to achieve this please?
Upvotes: 1
Views: 1514
Reputation: 189515
In order to set a binding on a DependencyObject
that doesn't derive from FrameworkElement
you need to use the BindingOperations.SetBinding
static method:-
SolidColorBrush backgroundBrush = new SolidColorBrush();
Binding b = new Binding("Config.BackgroundColorInfo.Value");
BindingOperations.SetBinding(backgroundBrush, SolidColorBrush.ColorProperty, b);
Note the documentation indicates the you would get an exception if the target is not of type FrameworkElement
but the documentation is out of step with the capabilities of Silverlight 4.
Edit
Having said that since you already have a class that your exposing as a Config
property why not have this class simply expose a "BackgoundBrush" property of type Brush
?
Upvotes: 3