[英]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. 我有一个WPF项目,在其中我以编程方式在ViewModel中动态设置某些元素的样式。
I'm defining my Style properties like so: 我正在定义我的Style属性,如下所示:
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; }
set
{
keyTypeValueMeaningStyle = value;
OnPropertyChanged(new PropertyChangedEventArgs("KeyTypeValueMeaningStyle"));
}
}
// ...later in the code...
if (error)
{
...
KeyTypeValueMeaningStyle = errorTextStyle;
}
else
{
...
KeyTypeValueMeaningStyle = okTextStyle;
}
And using it in my XAML like so: 像这样在我的XAML中使用它:
Style="{Binding KeyTypeValueMeaningStyle, UpdateSourceTrigger=PropertyChanged}"
This all works perfectly fine; 一切都很好。 however, I'm trying to streamline a bit more and instead of having
okTextStyle
set to a named style in my ResourceDictionary, I simply want it set to my base TextBox
style defined in my ResourceDictionary, but I don't know if this is possible. 但是,我正在尝试简化一些方法,而不是将
okTextStyle
设置为ResourceDictionary中的命名样式,我只是希望将其设置为ResourceDictionary中定义的基本TextBox
样式,但是我不知道这是否可行。
I've tried setting to null or blank such as this, but it does not work. 我尝试设置为null或诸如此类的空白,但是它不起作用。
private static Style okTextStyle = null As Style;
I've also tried doing similar things in my else
block but it doesn't work either. 我也尝试在我的
else
块中做类似的事情,但这也不起作用。 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. 我猜想因为在我的XAML中我总是在定义一个样式,所以它需要一个有效的样式引用,而不仅仅是空值或空白值。
Admittedly, this is a First-World programming issue as everything is working fine. 诚然,这是第一世界编程问题,因为一切都很好。 But the
SimpleTextBox
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. 但是,此时
SimpleTextBox
定义只是基准样式的重复,如果可能的话,我正在尝试简化一些样式,并且不使用重复的样式。 Can this be done? 能做到吗?
Application.Current.FindResource(typeof(TextBox));
If you want to be a little more persnickety, look at FrameworkElement.DefaultStyleKey
. 如果您想让自己更坚强一些,请查看
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. 顺便说一句,
null As Style
返回与不进行强制转换的null
完全相同的null
。 If I were on the C# team, I would have the compiler give you an Otiose Cast Warning on that line. 如果我在C#团队中,我希望编译器在该行上给您一个Otiose Cast警告。 That's not the only reason I'll never be on the C# team, but it's a good place to start.
这不是我永远不会加入C#团队的唯一原因,但这是一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.