Set Style Setter value from code-behind at runtime

烂漫一生 提交于 2019-12-11 04:22:41

问题


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.



来源:https://stackoverflow.com/questions/8593580/set-style-setter-value-from-code-behind-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!