Set Style Setter value from code-behind at runtime

2019-07-26 17:25发布

问题:

In silverlight, there is a known textbox caret bug that is discussed here: http://forums.silverlight.net/p/165276/423268.aspx

As a workaround, an attached behaviour is used that allows to specify the color for TextBox caret explicitly.

Therefore I have the following setter in my TextBox style:

<Style x:Key="NameEditStyle" TargetType="TextBox">
            <Setter Property="Utilities:FixCaretBrushBehavior.CaretBrush" Value="White" />

My application is running on Windows Phone, where there can be both White and Black backgrounds for the TextBoxes. I need to conditionally modify whether the caret will appear White to Black. (which is equivalent to setting a Value of the property).

How can I conditionally change this particular property in a style setter from code?

I have tried giving a property an x:Name and trying to reference it in code-behind, but the property is always null, so I can't adjust it's value.

回答1:

There is no way in WPF/SL/WP7 to change a style after it is loaded because the Style.IsSealed will be true. What you can do is to create new style based on the old one and change the TextBoxes style to the new style:

<Style x:Key="NameEditStyle" TargetType="TextBox">
    <Setter Property="Utilities:FixCaretBrushBehavior.CaretBrush" Value="White" />
    ...
</Style>

<Style x:Key="BlackNameEditStyle" TargetType="TextBox" BasedOn="{StaticResource NameEditStyle}">
    <Setter Property="Utilities:FixCaretBrushBehavior.CaretBrush" Value="Black" />
</Style>

Alternatively you can also create this new style during runtime as described here in the article.