绑定 WPF 样式 [英] Binding for WPF Styles
问题描述
我正在尝试创建一个自定义控件 - 一个按钮 - 它将根据数据上下文中的属性值应用多种样式.
I'm trying to create a custom control - a button - which will have multiple styles applied to it depending on the value of a property within the data context.
我在想的是使用类似的东西:
What I was thinking is using something similar to:
<Button Style="{Binding Path=ButtonStyleProperty, Converter={StaticResource styleConverter}}" Text="{Binding Path=TextProp}" />
在代码中...实现一个 IValueConverter,它在 ConvertTo
方法中执行类似于以下代码的操作:
And in code... Implement an IValueConverter which does something similar to the code below in the ConvertTo
method:
switch(value as ValueEnums)
{
case ValueEnums.Enum1:
FindResource("Enum1ButtonStyle") as Style;
break;
... and so on.
}
但是我不完全确定如何拉出样式对象,即使这是可能的......
However I'm not entirely sure about how to pull out the style object and even if this is possible at all...
同时我正在做的是处理 DataContextChanged
事件,然后将处理程序附加到绑定到按钮的对象的 PropertyChanged
事件 - 然后运行那里的 switch 语句.
What I am doing in the mean time is handling the DataContextChanged
event, then attaching a handler to the PropertyChanged
event of the object being bound to the button - then running the switch statement in there.
它不是很完美,但在我找到更好的解决方案之前,这似乎是我必须使用的.
Its not quite perfect but until I can find a better solution it seems like that is what I'll have to use.
推荐答案
如果您想替换整个样式(而不仅仅是其中的元素),那么您可能会将这些样式存储在资源中.您应该能够执行以下操作:
If you want to replace the whole style (rather than just elements of it) then you'll probably be storing those styles in resources. You should be able to do something along the lines of:
<Button>
<Button.Style>
<MultiBinding Converter="{StaticResource StyleConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="MyStyleString"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.Style>
</Button>
通过使用 MultiBinding 并使用 Self 作为第一个绑定,我们可以在转换器中查找资源.转换器需要实现 IMultiValueConverter(而不是 IValueConverter)并且看起来像这样:
By using a MultiBinding and using Self as the first binding we can then lookup resources in our converter. The converter needs to implement IMultiValueConverter (rather than IValueConverter) and can look something like this:
class StyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FrameworkElement targetElement = values[0] as FrameworkElement;
string styleName = values[1] as string;
if (styleName == null)
return null;
Style newStyle = (Style)targetElement.TryFindResource(styleName);
if (newStyle == null)
newStyle = (Style)targetElement.TryFindResource("MyDefaultStyleName");
return newStyle;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
这不是我经常做的事情,但应该可以凭记忆:)
It's not something I do very often, but that should work from memory :)
这篇关于绑定 WPF 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!