2

当布尔变量为真时,我需要更改标签和按钮的背景(返回默认颜色为假)。所以我写了一个附加属性。到目前为止看起来像这样:

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 中设置该颜色(以及默认颜色)。所以我可以决定背景切换的两种颜色。我怎样才能做到这一点?

4

2 回答 2

1

为什么不使用 DataTrigger 呢?

<Style x:Key="FilePathStyle" TargetType="TextBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=AddButton, Path=IsEnabled}" Value="True">
            <Setter Property="Background" Value="#FFEBF7E1" />
        </DataTrigger>

        <DataTrigger Binding="{Binding ElementName=AddButton, Path=IsEnabled}" Value="False">
            <Setter Property="Background" Value="LightYellow" />
        </DataTrigger>
    </Style.Triggers>
</Style>

.
.
.
<TextBox Style="{StaticResource FilePathStyle}" x:Name="filePathControl" Width="300" Height="25" Margin="5" Text="{Binding SelectedFilePath}" />
于 2014-10-17T13:22:50.287 回答
1

您可以有多个附加属性。访问它们很容易,有静态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"/>
于 2014-10-17T13:36:15.367 回答