我找到了解决方案。这不是微不足道的,而是有效的。假设我们有一个UserControl
包含 aTextBox
和 ather 控件的自定义。我们希望能够根据某些bool UserControl.IsSomething
依赖属性为每个内部控件分配样式。首先我们必须声明另一个依赖属性Style UserControl.AlternativeStyle
。然后我们附加一个事件处理程序IsSomething
以切换当前Style
和AlternativeStyle
何时IsSomething
更改:
public static DependencyProperty AlternativeStyleProperty =
DependencyProperty.Register(
"AlternativeStyle",
typeof(Style),
typeof(MyUserControl));
public Style AlternativeStyle
{
get { return (Style)GetValue(AlternativeStyleProperty); }
set { SetValue(AlternativeStyleProperty, value); }
}
public static DependencyProperty IsSomethingProperty =
DependencyProperty.Register(
"IsSomething",
typeof(bool),
typeof(MyUserControl),
new PropertyMetadata(true, IsSomethingProperty_Changed));
public bool IsSomething
{
get { return (bool)GetValue(IsSomethingProperty); }
set { SetValue(IsSomethingProperty, value); }
}
private static void IsSomethingProperty_Changed(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
// Swap styles
// e.g.
// var tempStyle = Style;
// Style = AlternativeStyle;
// AlternativeStyle = tempStyle;
}
更难的部分是关于AlternativeStyle
在 custom 之外设置UserControl
。下面是如何在托管我们自定义控件的窗口的 XAML 中实现这一点:
<Window.Resources>
<Style x:Key="DefaultTextBoxStyle" TargetType="TextBox">
<Setter Property="Background" Value="Red"/>
</Style>
<Style x:Key="DefaultUserControlStyle" TargetType="local:MyUserControl">
<Style.Resources>
<Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBoxStyle}">
<Setter Property="Background" Value="Blue"/>
</Style>
</Style.Resources>
</Style>
<Style x:Key="AlternativeUserControlStyle" TargetType="local:MyUserControl" BasedOn="{StaticResource DefaultUserControlStyle}">
<Style.Resources>
<Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBoxStyle}">
<Setter Property="Background" Value="Green"/>
</Style>
</Style.Resources>
</Style>
<Style TargetType="local:MyUserControl" BasedOn="{StaticResource DefaultUserControlStyle}">
<Setter Property="AlternativeStyle" Value="{StaticResource AlternativeUserControlStyle}"/>
</Style>
</Window.Resources>
上述样式将自动添加到所有实例中MyUserControl
,当我们更改IsSomething
值时,替代样式将应用于 changed 的所有者IsSomething
。