Get button style name
I have several styles on Window.Resour开发者_如何学编程ces that I apply to several buttons with C#. Then I need to change the style but first I need to know what is the current style that is applied to the button I want to change the style. I can't find the way to get the style name from the button!
Did you try Button.Style
property? If explcit setting of style is done using resource Key
then you should get the current style of the button using Button.Style
propetry otherwise it is a little tricky to gather all Style
related information at a control level.
And there are reasons for this. Styles are inherited and could be overriden at distinct element scopes such as App, Window, UserControl, Ancestor UIElements and finally the individual control. So when you access Button.Style
property you get a style that was the last immediate style applied to the Button
. If the style is BasedOn
another Style
then Style.BasedOn
will give you the parent / base Style
. Again if that BasedOn
style is derived from another Style
we will get that as Style.basedOn.BasedOn
... etc.
I hope this makes sense. :-)
I think you are making a mistake in terms of design/architecture if you approach your issue this way. If you need to change styles conditionally you can create UI-elements based on objects which hold the relevant information using data-binding and templating.
That's a good question (+1).
This is just my thought which may not be very accurate. I doubt if it makes sense to get a style for a UI control. Suppose you apply style "style1" to an UI control and then you can set individual attributes like foreground/background.... Now, what would be the style?
If you want to maintain/track the state of the button, that should be handled either as visual states or in your code behind (ViewModel/Model) probably.
See: Style
public void FooFunc()
{
Button myButton = ...;
Console.WriteLine("The Style: {0}", myButton.Style);
}
I think that's what you're looking for?
Thanks for your answers, I'm using this function from another stackoverflow.. it works and returns the style name into a string!
static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
{
foreach (object key in dictionary.Keys)
{
if (dictionary[key] == resourceItem)
{
return key.ToString();
}
}
return null;
}
@Max, I'm new to WPF, and had to toggle my Border object's style between one of two known Styles it can have. Rather than use the linear search in FindNameFromResource, I instead instead did this ...
Style normal = (Style)this.Resources["NormalBorder"];
Style strong = (Style)this.Resources["StrongBorder"];
border.Style = border.Style == normal ? strong : normal;
精彩评论