2014-10-17 59 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