bassrek bassrek - 1 month ago 7x
C# Question

Programmatically setting WPF style to baseline style

I have a WPF project where I am dynamically setting the Style of certain elements programmatically in my ViewModel.

I'm defining my Style properties like so:

private static Style okTextStyle = Application.Current.FindResource("SimpleTextBox") as Style;
private static Style errorTextStyle = Application.Current.FindResource("SimpleTextBoxError") as Style;

private Style keyTypeValueMeaningStyle = okTextStyle;
public Style KeyTypeValueMeaningStyle
get { return keyTypeValueMeaningStyle; }
keyTypeValueMeaningStyle = value;
OnPropertyChanged(new PropertyChangedEventArgs("KeyTypeValueMeaningStyle"));

// ...later in the code...

if (error)
KeyTypeValueMeaningStyle = errorTextStyle;
KeyTypeValueMeaningStyle = okTextStyle;

And using it in my XAML like so:

Style="{Binding KeyTypeValueMeaningStyle, UpdateSourceTrigger=PropertyChanged}"

This all works perfectly fine; however, I'm trying to streamline a bit more and instead of having
set to a named style in my ResourceDictionary, I simply want it set to my base
style defined in my ResourceDictionary, but I don't know if this is possible.

I've tried setting to null or blank such as this, but it does not work.

private static Style okTextStyle = null As Style;

I've also tried doing similar things in my
block but it doesn't work either. I'm guessing that since in my XAML I'm always defining a style, it wants a valid style reference in there, not just a null or blank value.

Admittedly, this is a First-World programming issue as everything is working fine. But the
definition is just a duplicate of the baseline style at this point and I'm trying to streamline a bit if possible and not have duplicate styles. Can this be done?


If you want to be a little more persnickety, look at FrameworkElement.DefaultStyleKey.

That said, this is not something that a viewmodel ought to be responsible for.

By the way, null As Style returns exactly the same null as null without the cast. If I were on the C# team, I would have the compiler give you an Otiose Cast Warning on that line. That's not the only reason I'll never be on the C# team, but it's a good place to start.