获取来自定义控件(继承自Contro基类)的定义在Generic.xaml或其他*.xaml中的对象

不管在SL或WPF中,在创建自定义控件时,我们有可能需要在Generic.xaml中定义多个控件的Style,定义的多了找起来就很麻烦,如果在单个文件里定义好,然后在Generic.xaml中包含(include)岂不是很好,Generic.xaml代码如下:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/WpfCustomControlLibrary1;component/CustomControl1.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

CustomControl1.cs:

namespace WpfCustomControlLibrary1
{
    public class CustomControl1 : Control
    {
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
        }
    }
}

CustomControl1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfCustomControlLibrary1"
                    >
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <WrapPanel>
                                <Label Background="Yellow">昨天</Label>
                                <Label Background="Green">今天</Label>
                                <Label Background="Orange">明天</Label>
                            </WrapPanel>
                        </Grid>

                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

依赖属性标识符字段: DefaultStyleKeyProperty

若要为继承自 Control 的控件提供默认的 Style,请将 DefaultStyleKey 属性设置为相同类型的 TargetType 属性。如果您没有设置 DefaultStyleKey,则将使用基类的默认样式。例如,如果称为 NewButton 的控件继承自 Button,要使用新的默认 Style,请将 DefaultStyleKey 设置为类型 NewButton。如果您没有设置 DefaultStyleKey,则会将 Style 用于 Button

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值