当布尔变量为真时,我需要更改标签和按钮的背景(返回默认颜色为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}" />
它工作正常。在viewmodel中设置相应变量test
时,backgroundcolor将更改为LimeGreen
。
我的问题:
颜色LimeGreen
是硬编码的。我也想在XAML中设置该颜色(以及默认颜色)。所以我可以决定背景切换的颜色。我怎么能这样做?
答案 0 :(得分: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"/>
答案 1 :(得分: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}" />