您可以使用 anenum
来提供您想要的固定值Xaml
,然后您可以使用PropertyChangedCallback
on 那enum
DependencyProperty
来更改Brush
.
这是一个非常简单的例子。
代码:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
public BrushType BrushType
{
get { return (BrushType)GetValue(BrushTypeProperty); }
set { SetValue(BrushTypeProperty, value); }
}
// Using a DependencyProperty as the backing store for BrushType. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BrushTypeProperty =
DependencyProperty.Register("BrushType", typeof(BrushType), typeof(UserControl1)
, new PropertyMetadata(BrushType.None, new PropertyChangedCallback(OnBrushTypeChanged)));
private static void OnBrushTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var userControl = d as UserControl1;
if (e.NewValue is BrushType)
{
userControl.MyBrush = userControl.FindResource(e.NewValue.ToString()) as Brush;
}
}
public Brush MyBrush
{
get { return (Brush)GetValue(MyBrushProperty); }
set { SetValue(MyBrushProperty, value); }
}
// Using a DependencyProperty as the backing store for MyBrush. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyBrushProperty =
DependencyProperty.Register("MyBrush", typeof(Brush), typeof(UserControl1), new PropertyMetadata(null));
}
public enum BrushType
{
None,
BrushA,
BrushB,
BrushC
}
xml:
<UserControl x:Class="WPFListBoxGroupTest.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<SolidColorBrush x:Key="BrushA" Color="Red" />
<SolidColorBrush x:Key="BrushB" Color="Yellow" />
<SolidColorBrush x:Key="BrushC" Color="Blue" />
</UserControl.Resources>
<Grid Background="{Binding MyBrush}" />
</UserControl>
用法:
<StackPanel Orientation="Horizontal">
<local:UserControl1 BrushType="BrushA" />
<local:UserControl1 BrushType="BrushB" />
<local:UserControl1 BrushType="BrushC" />
</StackPanel>
结果: