【发布时间】:2018-01-24 09:45:26
【问题描述】:
我正在尝试构建一个自定义 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 模板:
<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>
但是颜色仍然是灰色的。任何想法我做错了什么?
【问题讨论】:
标签: c# wpf enums custom-controls