BasedOn=“{StaticResource {x:Type TextBox}}” in Code Behind for Style

强颜欢笑 提交于 2019-12-05 10:16:06

问题


How can you set the following in code behind?

<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">

I'm using a Theme merged in App.xaml. It works great for all Controls but when I define a Style for something, e.g. TextBox, the Theme Style doesn't get picked up unless I use BasedOn like above, instead it gets the default TextBox Style.

Now I'm creating a DataGridTextColumn in code behind and I can't get the BasedOn part to work for the EditingElementStyle

Style editingStyle = new Style(typeof(TextBox));
editingStyle.BasedOn = ...?;

Any suggestions? Also, is there any way to get the Theme Style instead of the default Style applied without using BasedOn?

Thanks


回答1:


Try this:

editingStyle.BasedOn = (Style) FindResource(typeof (TextBox))

And I don't know any way how you can make it apply the Theme style without specifying BasedOn. If there is such a way, I would like to know it too...




回答2:


This should work:

Style baseStyle = new Style(typeof(TextBox));
Style editingStyle = new Style(typeof(TextBox));
editingStyle.BasedOn = baseStyle;

You can also do it in the constructor:

Style editingStyle = new Style(typeof(TextBox), baseStyle);



回答3:


I like the answer of Pavlo Glazkov, but it does not compile.

FindResource is (non-static) member of FrameworkElement. It is required to identify the context of the search request.

So I recommend this:

style.BasedOn = (Style)frameworkElement.FindResource(typeof(TextBox));


来源:https://stackoverflow.com/questions/5195030/basedon-staticresource-xtype-textbox-in-code-behind-for-style

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