您可以使用enum
爲您提供在Xaml
想要的固定值,那麼你可以使用PropertyChangedCallback
上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
}
的XAML:
<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>
結果:
這裏
好了,我就在想,我有一個用戶控件錯了,但我不我其實有一個資源字典,我則有基於控制。我在你的代碼中進行了探索,這幾乎是一種享受。未找到BrushA/B/C資源。如果我將它們放在Page級別作爲頁面資源,那麼它會編譯,但不會設置顏色。我會將你的答案標記爲正確的,因爲它符合我的要求。我的錯我把電線交叉了。你能建議我應該把SolidcolorBrush資源放在資源字典中嗎?非常感謝你花了這麼多時間。 – MikeyTT 2013-05-16 22:21:21
如果您僅使用路徑上的畫筆,然後將其放在中或父容器中,如果您不使用UserControl,則可以將畫筆放置在您的控件的任何位置。 FrameworkElements擁有自己的資源 –
2013-05-16 22:30:32
謝謝。我會在週末對此進行更多的研究,看看它對我的影響。 – MikeyTT 2013-05-17 08:39:50