3

I want to bind the style of button on the basis of if else condition. I have created one string property in the viewmodel and bind to the button's style attribute like this:

<Button x:Name="copd" Content="COPD" 
    Command="{Binding COPDReadingsCommand}" 
    Style="{DynamicResource ResourceKey={Binding CheckCopd}}"  
    HorizontalAlignment="Center" VerticalAlignment="Center" 
    Margin="20" FontWeight="Bold" />

I am looping through the resourceDictionary and getting all the keys. Using if else i am changing the string property value(CheckCopd) in if else.

I am getting the desired values in if else but style is not getting applied to the button when I execute my application. It only displays the generic button style.

How to bind the DynamicResource ?

Kindly Suggest?

Thank You.

Tarun
  • 393
  • 1
  • 6
  • 22
  • If you can show a little more about what you are trying to accomplish, then it would be easier to show a viable solution. – CodeNaked Apr 12 '11 at 13:37
  • I want to change the style of the button on the basis of if else condition when first the wpf application is getting loaded. On application loaded using if, there will be one style of button and in else part, there will be another. Style is nothing but a image. – Tarun Apr 13 '11 at 07:27
  • Can you please post your two Styles or a trimmed down version? – CodeNaked Apr 13 '11 at 11:20
  • @CodeNaked. I have used the DataTriggers and its working fine. Thanks – Tarun Apr 13 '11 at 11:26

2 Answers2

3

You cannot use bindings on the DynamicResource properties, as it does not derive from DependencyObject. You would either need to set the Style property directly from code-behind, or just use a Binding.

You could use a Style for the Button type, which has a DataTrigger based on a custom property that dynamically changes the look. But in this case, you need a single Style, which changes it's setters based on your condition. It would not allow you to change the Style property itself dynamically.

CodeNaked
  • 40,753
  • 6
  • 122
  • 148
0

You can try this... I came up with a way to create a DynamicResourceBinding on which you can use a converter to achieve the results you want. (You theoretically could also just use styles and triggers, but I digress...)

How do you create a DynamicResourceBinding that supports Converters, StringFormat?

Community
  • 1
  • 1
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286