我尝试使用可能导致背景颜色发生变化的状态来构建自定义ContentControl。
因此我定义了以下枚举:
public enum OrderSourceState
{
Idle,
Busy,
}
我的customControl类中的DependencyProperty:
public class BorderWithState : ContentControl
{
public static readonly DependencyProperty OrderStateProperty =
DependencyProperty.Register("OrderState", typeof(OrderSourceState),
typeof(BorderWithState), new FrameworkPropertyMetadata(OrderSourceState.Idle));
// .NET Property wrapper
public OrderSourceState OrderState
{
get { return (OrderSourceState)GetValue(OrderStateProperty); }
set { SetValue(OrderStateProperty, value); }
}
static BorderWithState()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BorderWithState), new FrameworkPropertyMetadata(typeof(BorderWithState)));
}
}
最后我定义了以下XAML-Template:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MasterEKanBan"
xmlns:customControls="clr-namespace:MasterEKanBan.WPF">
<Style TargetType="{x:Type customControls:BorderWithState}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="LightGray"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type customControls:BorderWithState}">
<Border x:Name="border" Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter Content="{TemplateBinding Content}"/>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding OrderState}" Value="{x:Static local:OrderSourceState.Idle}">
<Setter TargetName="border" Property="Background">
<Setter.Value>
<SolidColorBrush Color="LightGray"/>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding OrderState}" Value="{x:Static local:OrderSourceState.Busy}">
<Setter TargetName="border" Property="Background">
<Setter.Value>
<SolidColorBrush Color="LightGreen"/>
</Setter.Value>
</Setter>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
最后,我通过以下方式嵌入了自定义控件:
<customControls:BorderWithState Grid.Column="0" Grid.Row="0" BorderThickness="5" BorderBrush="Black" Margin="20" OrderState="{x:Static local:OrderSourceState.Busy}" >
<Label Content="Mobile-RFID" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="30"/>
</customControls:BorderWithState>
但颜色仍然是灰色的。任何想法我做错了什么?
答案 0 :(得分:1)
您的触发器是错误的,即您使用DataTrigger
与Binding="{Binding OrderState}"
,它会尝试在当前OrderState
上找到DataContext
属性并绑定到它。你想要的是将触发器基于模板化控件上的属性值。为此,您应该使用常规Trigger
和相应的Property
值:
<Trigger Property="OrderState" Value="(...)">
(...)
</Trigger>
或者,至少为DataTrigger
绑定指定正确的来源:
<DataTrigger Binding="{Binding OrderState, RelativeSource={RelativeSource Self}}" Value="(...)">
(...)
</DataTrigger>