我有一个名为 Heading 的自定义 WPF 控件,我使用 Theme.xaml 在应用程序范围内设置该控件的样式,并在其中设置了 ControlTemplate。我正在使用 BasedOn 为某些窗口调整此样式。这在设计器中有效,但在运行时失败。结果是一个不可见的控件,因为它没有控件模板。
此项目中的多个自定义控件都会发生这种情况。这些控件在其他项目中运行良好。
Theme.xaml中的样式:
<Style TargetType="{x:Type controls3:Heading}">
<Setter Property="Focusable" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls3:Heading}">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{TemplateBinding Text}"
FontWeight="Bold"
FontSize="12" LineHeight="12"
VerticalAlignment="Center"
LineStackingStrategy="BlockLineHeight"
Foreground="{StaticResource SolidWorksTextGrayBrush}"/>
<Button Grid.Column="1"
ToolTip="{TemplateBinding Button1Tooltip}"
Width="25" Height="25"
VerticalAlignment="Center"
Margin="10 0 0 0"
Command="{TemplateBinding Button1Command}"
Visibility="{TemplateBinding ShowButton1, Converter={StaticResource BooleanToVisibilityConverter}}"
Focusable="False">
<Image Source="{TemplateBinding Button1ImageSource}"
Width="{TemplateBinding Button1ImageWidth}"/>
</Button>
<Button Grid.Column="2"
ToolTip="{TemplateBinding Button2Tooltip}"
Width="25" Height="25"
VerticalAlignment="Center"
Margin="10 0 0 0"
Command="{TemplateBinding Button2Command}"
Visibility="{TemplateBinding ShowButton2, Converter={StaticResource BooleanToVisibilityConverter}}"
Focusable="False">
<Image Source="{TemplateBinding Button2ImageSource}"
Width="{TemplateBinding Button2ImageWidth}"/>
</Button>
</Grid>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
窗口中的样式:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/ProjectName.Addin;component/Windows/Theme.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="controls:Heading" BasedOn="{StaticResource {x:Type controls:Heading}}">
<Setter Property="Margin" Value="5 10 0 5" />
</Style>
</ResourceDictionary>
</Window.Resources>
我做了很多调试并注意到:
知道这里可能出了什么问题吗?
尝试重写自定义控件构造函数中的defaultstylekey,如下所示:
public class Heading
{
static Heading()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Heading),
new FrameworkPropertyMetadata(typeof(Heading)));
}
}