1

I have an issue with using Styles on DataTemplates in WPF ... It appears to suck. Suppose that you define a DataTemplate:

<DataTemplate DataType="{x:Type local:DataSource}">
    <TextBox Style="{StaticResource TextBoxStyle}" Text="{Binding Path=myData}"  />
</DataTemplate>

Is there now any way to dynamically style this element? (eg. change the background color in some parts of the application) My problems are:

  • if you set a style in some parent-control, it gets ignored since there is already a style in the datatemplate
  • if you set a property on a parent-control, it doesn't get inherited since styles have precedence over property inheritence

Does anyone see a way to do this?

1 Answer 1

1

you can try it using DynamicResource

<DataTemplate DataType="{x:Type local:DataSource}">
        <TextBox Style="{DynamicResource TextBoxStyle}" Text="{Binding Path=myData}"  />
</DataTemplate>

and then later if you need to change the style in any other control. you can just declare same resource with same key for that control. Suppose you are using it in ListBox.

 <ListBox>
        <ListBox.Resources>
            <Style x:Key="TextBoxStyle" TargetType="TextBox">
               <!--define changed style.-->
            </Style>
        </ListBox.Resources>
    </ListBox>

new style will apply over there.

1
  • Hm, I didn't expect this to work, but it did ... I saw DynamicResource as a resource that can change, I didn't realise it had anything to do with how a resource is resolved. Strange ...
    – kodu
    Jan 14, 2013 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.