zoukankan      html  css  js  c++  java
  • WPF为控件扩展的附加属性不起作用需要注意的地方

    我给WPF控件扩展了一个名为CornerRadius的附加属性,以便于所有控件在重写ControlTemplate的时候,在ControlTemplate中先加上一个Border,然后利用附加的CornerRadius,设置圆角属性,看起来是这样的:

    <ControlTemplate TargetType="{x:Type TextBox}">
      <Border x:Name="TextBorder"
        CornerRadius="{Binding (ex:ControlExtention.CornerRadius), RelativeSource={RelativeSource TemplatedParent}}"
        BorderThickness="{Binding BorderThickness,RelativeSource={RelativeSource TemplatedParent}}"
        BorderBrush="{Binding BorderBrush,RelativeSource={RelativeSource TemplatedParent}}"
        Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}">
        <ScrollViewer x:Name="PART_ContentHost"
          FontSize="{Binding FontSize,RelativeSource={RelativeSource TemplatedParent}}"
          Padding="{Binding Padding,RelativeSource={RelativeSource TemplatedParent}}"
          Foreground="{Binding Foreground,RelativeSource={RelativeSource TemplatedParent}}"/>
      </Border>
      <ControlTemplate.Triggers>
        <Trigger Property="IsKeyboardFocusWithin"  Value="True">
          <Setter Property="BorderBrush" TargetName="TextBorder" Value="{Binding (ex:ControlExtention.FocusBackground), RelativeSource={RelativeSource TemplatedParent}}"/>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
    高亮加粗的 ex:ControlExtention.CornerRadius 即为使用的附加属性,需要在资源字典根标签中,自定义扩展属性所在的命名空间

    看起来是这样的

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:ex="clr-namespace:Test.Extention">
    
    ......
    </ResourceDictionary>
    
    
    其中 ex 为当前自定义的命名空间,然而在UserControl中调用的时候,
    
    
    <TextBox Style="{DynamicResource BaseTextBoxStyle}" />
    
    

    发现圆角不起作用。

    思考可能是UserControl中需要到扩展附加属性的类中去取值,但是 UserControl 本身没有引用Test.Extention的命名空间,于是加上

    xmlns:extention="clr-namespace:Test.Extention;assembly=Test"

    发现依然不行,最后发现是 extention 两次起的名字不一样,改成ex就可以,看来xmlns和类中的命名空间是一样的,虽然在单一文件定义,但却是全局的。

    此文备忘。

  • 相关阅读:
    hashCode()相同,equals()也一定为true吗?
    什么是装箱?什么是拆箱?装箱和拆箱的执行过程?常见问题?
    LOJ114_k 大异或和_线性基
    BZOJ_4459_[Jsoi2013]丢番图_数学+分解质因数
    BZOJ_4184_shallot_线段树按时间分治维护线性基
    BZOJ_2844_albus就是要第一个出场_线性基
    BZOJ_3105_[cqoi2013]新Nim游戏_线性基+博弈论
    BZOJ_1195_[HNOI2006]最短母串_AC自动机+BFS+分层图
    BZOJ_3881_[Coci2015]Divljak_AC自动机+dfs序+树状数组
    BZOJ_1532_[POI2005]Kos-Dicing_二分+网络流
  • 原文地址:https://www.cnblogs.com/ywei221/p/4568915.html
Copyright © 2011-2022 走看看