我正在开发一个 WPF 项目,在其中我覆盖了 CheckBox
控件以进行特殊操作。这部分功能已经正常工作。
我的问题是,从主题应用的 ControlTemplate
(来自 codeplex 的 shinyred.xaml)没有被应用到我覆盖后的控件上。是否有一种方法可以继承 CheckBox
的ControlTemplate
以供我的新控件使用?
我找到的所有示例都集中在为CheckBox
继承样式,但没有关于 ControlTemplate
的内容。
我正在开发一个 WPF 项目,在其中我覆盖了 CheckBox
控件以进行特殊操作。这部分功能已经正常工作。
我的问题是,从主题应用的 ControlTemplate
(来自 codeplex 的 shinyred.xaml)没有被应用到我覆盖后的控件上。是否有一种方法可以继承 CheckBox
的ControlTemplate
以供我的新控件使用?
我找到的所有示例都集中在为CheckBox
继承样式,但没有关于 ControlTemplate
的内容。
<Style TargetType="<your type>">
<Setter Property="Template" Value="{StaticResource <existing template resource name>}"/>
</Style>
记住@Aviad所说的,以下是一个解决方法:
假设你有一个定义了模板的Button
,你想要继承它,那么就像这样将你的CustomButton
定义为自定义控件:
public class CustomButton : Button
{
static CustomButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
typeof(string), typeof(CustomButton), new UIPropertyMetadata(null));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
然后转到您的Generic.xaml并定义以下内容:
<Style
x:Key="CustomButtonStyle" TargetType="{x:Type local:CustomButton}">
<Setter Property="FontSize" Value="18" /> <!--Override the font size -->
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomButton}">
<Button Style="{StaticResource ButtonStyleBase}"
Height="{TemplateBinding Height}"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:CustomButton}}, Path=Command}"
CommandParameter="{Binding}"
Width="{TemplateBinding Width}">
<Grid>
<StackPanel>
<Image Source="Image/icon.jpg" />
<TextBlock Text="{TemplateBinding Text}"></TextBlock>
</StackPanel>
</Grid>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>