Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Style using Binding in XAML

I need to set a Style of a given control according to some configuration value in Silverlight. I would like to have a possibility of choosing a Style for a control from two available styles (static resources). I was trying to do something like:

<TextBox Style="{Binding ABC}"/>

where

public string ABC
{
    get {return "{StaticResource MyStyle}";}
}

Unfortunately, that does not work.

Do you have any ideas?

Thanks in advance!

Cheers

like image 319
Jamie Avatar asked Feb 06 '11 22:02

Jamie


People also ask

How do you use style in XAML?

The most common way to declare a style is as a resource in the Resources section in a XAML file. Because styles are resources, they obey the same scoping rules that apply to all resources. Put simply, where you declare a style affects where the style can be applied.

How do I bind with XAML?

One-Way Data Binding The following XAML code creates four text blocks with some properties. Text properties of two text blocks are set to “Name” and “Title” statically, while the other two text blocks Text properties are bound to “Name” and “Title” which are class variables of Employee class which is shown below.

What is style in XAML?

You can customize the appearance of your apps in many ways by using the XAML framework. Styles let you set control properties and reuse those settings for a consistent appearance across multiple controls.

What is binding mode in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.


1 Answers

You are close. You need to be binding the Style property to a property of type Style though (not a string representing a static resource lookup).

You have two options for storage of the style and this will determine what the property looks like. Either put the style in the pages resources or in the App resources, and then you ABC property will look like one of the following:

// using page resources
public Style ABC
{
    get { return (Style) this.Resources["_myStyle"]; }
}

// using application resources
public Style ABC
{
    get { return (Style) App.Current.Resources["_myStyle"]; }
}

Where _myStyle is the value the style has for its x:Key property in the resource dictionary.

like image 77
Simon Fox Avatar answered Oct 01 '22 04:10

Simon Fox