【发布时间】:2014-12-13 01:57:20
【问题描述】:
当布尔变量为真时,我需要更改标签和按钮的背景(假时返回默认颜色)。所以我写了一个附加属性。到目前为止看起来像这样:
public class BackgroundChanger : DependencyObject
{
#region dependency properties
// status
public static bool GetStatus(DependencyObject obj)
{
return (bool)obj.GetValue(StatusProperty);
}
public static void SetStatus(DependencyObject obj, bool value)
{
obj.SetValue(StatusProperty, value);
}
public static readonly DependencyProperty StatusProperty = DependencyProperty.RegisterAttached("Status",
typeof(bool), typeof(BackgroundChanger), new UIPropertyMetadata(false, OnStatusChange));
#endregion
private static void OnStatusChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as Control;
if (element != null)
{
if ((bool)e.NewValue)
element.Background = Brushes.LimeGreen;
else
element.Background = default(Brush);
}
}
}
我是这样使用它的:
<Label CustomControls:BackgroundChanger.Status="{Binding test}" />
它工作正常。当在视图模型中设置了相应的变量test时,背景色变为LimeGreen。
我的问题:
颜色LimeGreen 是硬编码的。我也想在 XAML 中设置该颜色(以及默认颜色)。所以我可以决定背景切换的两种颜色。我该怎么做?
【问题讨论】:
-
当
Status为真时,如何使用另外一个附加属性来指定颜色?还是将Status设为Brush类型? -
我正在努力制作一个(或两个)更多的属性。我如何在
OnStatusChanged中使用它们?
标签: c# wpf attached-properties brushes