WPF Silverlight 附加属性(AttachedProperty)

  本帖只考虑 附加属性 知识点 其余知识点和架构设置不在此讨论范围内 附加属性是特殊的依赖项属性 是对已有控件的扩展

 

  public class AttachedPropertyClass : DependencyObject
    {
        public static string GetAttachedPropertyName(DependencyObject obj)
        {
            return (string)obj.GetValue(AttachedPropertyNameProperty);
        }

        public static void SetAttachedPropertyName(DependencyObject obj, string value)
        {
            obj.SetValue(AttachedPropertyNameProperty, value);
        }

        public static readonly DependencyProperty AttachedPropertyNameProperty =
      DependencyProperty.RegisterAttached("AttachedPropertyName", typeof(string), typeof(AttachedPropertyClass), new PropertyMetadata(callback));

        private static void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var _Button = d as Button;
            _Button.Content = e.NewValue.ToString() + "调用";
            _Button.Foreground = new SolidColorBrush(Colors.Red);
        }
    }

 

 <Button Name="bt" Content="调用" Width="75" Height="35" local:AttachedPropertyClass.AttachedPropertyName="大庆油田">
            <Button.Template>
                <ControlTemplate TargetType="Button">                 
                    <TextBlock Text="{TemplateBinding Content}"/>
                </ControlTemplate>
            </Button.Template>
 </Button>

 

当然也可以直接绑定在附加属性上

 <Button Content="调用" Width="75" Height="35" local:AttachedPropertyClass.AttachedPropertyName="大庆油田">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <TextBlock Text="{TemplateBinding local:AttachedPropertyClass.AttachedPropertyName}"/>
                </ControlTemplate>
            </Button.Template>
  </Button>

 

也可以加上默认值 在没有设置对应值时使用的默认值

new PropertyMetadata("股份公司",callback)

 

需要注意的一点是 当其他元素绑定到此元素时需使用()括起来

比如:

 <TextBlock Text="{Binding ElementName=bt,Path=(local:AttachedPropertyClass.AttachedPropertyName)}"/>

TemplateBinding 除外

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值