2014-10-17 58 views
1

当布尔变量为true时,我需要更改标签和按钮的背景(在false时返回默认颜色)。所以我写了一个附加的属性。它看起来像这样至今:WPF用附加属性更改控件的背景

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时,backgroundcolor更改为LimeGreen

我的问题:

颜色LimeGreen是硬编码。我想在XAML中设置该颜色(以及默认颜色)。所以我可以决定后台切换哪种颜色。我怎样才能做到这一点?

+0

如何使用多一个附加属性来指定颜色,当'Status'是真的吗?或者让'Status'成为'Brush'类型? – Sinatr 2014-10-17 13:20:49

+0

我正在努力创造一个(两个)更多的属性。我如何在'OnStatusChanged'中使用它们? – 2014-10-17 13:22:19

回答

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"/> 
+0

好的,这是有效的。但是我如何在xaml的视图中设置这些属性? – 2014-10-17 13:43:57

0

为什么不使用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}" /> 
+0

目前我正在使用datatrigger。但是在我需要该功能的每个控件上编写所有这些行? – 2014-10-17 13:38:18

+0

我有点困惑。这些控制利用了他们都可以在一个地方(即风格)获得行为的风格。 – 2014-10-17 13:55:38