当在wpf中应用样式时,用户控件内的组合框消失
我试图将样式应用于组合框,但不是应用组合框本身消失。 请检查以下用于用户控制的xaml代码。
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Luna"
x:Class="Guardian.PAS.PASFramework.UI.WPF.PASComboBox"
xmlns:local="clr-namespace:Guardian.PAS.PASFramework.UI.WPF"
Height="26" Width="100" VerticalAlignment="Center" >
<UserControl.Resources>
<Style x:Key="comboBoxStyle" TargetType="{x:Type local:PASCustomComboBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:PASCustomComboBox}">
<ControlTemplate.Triggers>
<Trigger Property="local:PASCustomComboBox.IsEnabled" Value="false">
<Setter Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Canvas Name="canvas" Height="23" Width="Auto" VerticalAlignment="Center">
<Label Height="23" Name="lblCaption" Width="20" VerticalAlignment="Center">aaa</Label>
<local:PASCustomComboBox Height="23" x:Name="cmbComboBoxControl" VerticalAlignment="Center" Width="50"
IsEditable="True" Style="{StaticResource comboBoxStyle}">
</local:PASCustomComboBox>
<Button Height="23" Name="btnSearch" Width="25" Click="btnSearch_Click" Visibility="Collapsed"
VerticalAlignment="Center">...</Button>
<Label Height="23" Name="lblDescription" VerticalAlignment="Center" Width="20" Foreground="Blue">
</Label>
</Canvas>
</UserControl>
这里PASCustomComboBox是一个从组合框继承的类。
public class PASCustomComboBox : ComboBox
{
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Down || e.Key == Key.Up)
{
e.Handled = true;
return;
}
base.OnPreviewKeyDown(e);
}
}
问题在于你重新定义了ControlTemplate而没有任何可视化树:
<Style x:Key="comboBoxStyle" TargetType="{x:Type local:PASCustomComboBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:PASCustomComboBox}">
<ControlTemplate.Triggers>
<Trigger Property="local:PASCustomComboBox.IsEnabled" Value="false">
<Setter Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
你会想要风格上的触发器而不是控制模板:
<Style x:Key="comboBoxStyle" TargetType="{x:Type local:PASCustomComboBox}">
<Style.Triggers>
<Trigger Property="local:PASCustomComboBox.IsEnabled" Value="false">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
你不要在你的风格的控件模板中指定任何视觉元素,只是一个触发器。 它将渲染空模板iirc。
更好地编辑样式中的ComboBox的Trigger集合以添加该触发器,并且您将保留默认的ControlTemplate。
链接地址: http://www.djcxy.com/p/34473.html上一篇: combo box inside a user control disappears when style is applied in wpf
