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和类中的命名空间是一样的,虽然在单一文件定义,但却是全局的。

    此文备忘。

  • 相关阅读:
    1257 背包问题 V3(二分)
    全国高校绿色计算大赛 预赛第三阶段(Python)(随机数)
    全国高校绿色计算大赛 预赛第二阶段(Python)
    全国高校绿色计算大赛 预赛第一阶段(Python)
    全国绿色计算大赛 模拟赛第二阶段 (Python)
    全国绿色计算大赛 模拟赛第一阶段(Python)
    51node 1134 最长递增子序列 (数据结构)
    提高(Android)开发效率的工具与网站
    Android 打开方式选定后默认了改不回来?解决方法(三星s7为例)
    SharedPreferences 的另一种场景的用法
  • 原文地址:https://www.cnblogs.com/ywei221/p/4568915.html
Copyright © 2011-2022 走看看