[英]WPF change background of a control with an attached property
當布爾變量為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}" />
它工作正常。 當在視圖模型中設置了相應變量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"/>
為什么不使用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}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.