当 bool 变量为 true 时,我需要更改标签和按钮的背景(如果为 false,则返回默认颜色)。所以我写了一个附加属性。到目前为止看起来像这样:
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}" />
效果很好。当在 View 模型中设置相应的变量 test
时,背景颜色将更改为 LimeGreen
。
我的问题:
颜色LimeGreen
是硬编码的。我也想在 XAML 中设置该颜色(以及默认颜色)。这样我就可以决定背景在哪两种颜色之间切换。我该怎么做?
最佳答案
您可以拥有多个附加属性。访问它们很容易,有静态 Get..
和 Set..
方法,您可以向其中提供 DependencyObject
来附加您想要的属性值操作。
public class BackgroundChanger : DependencyObject
{
// make property Brush Background
// type "propdp", press "tab" and complete filling
private static void OnStatusChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as Control;
if (element != null)
{
if ((bool)e.NewValue)
element.Background = GetBrush(obj); // getting another attached property value
else
element.Background = default(Brush);
}
}
}
在 xaml 中它看起来像
<Label CustomControls:BackgroundChanger.Status="{Binding test}"
CustomControls:BackgroundChanger.Background="Red"/>
关于c# - WPF 更改具有附加属性的控件的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425771/