今天遇到一个需求,我需要在一个button里面添加一个自定义的属性。这个应该如何实现呢?
后来通过研究,发现可以使用附件属性来实现
写一个基础类
public class ElementBase
{
/// <summary>
/// 注册属性
/// public static readonly DependencyProperty Property = Utility.Property<T,T>(string,T);
/// </summary>
/// <typeparam name="thisType">this</typeparam>
/// <typeparam name="propertyType">如:string,bool</typeparam>
/// <param name="name">属性名</param>
/// <param name="defaultValue">属性值</param>
/// <returns></returns>
public static DependencyProperty Property<thisType, propertyType>(string name, propertyType defaultValue)
{
return DependencyProperty.Register(name.Replace("Property", ""), typeof(propertyType), typeof(thisType), new PropertyMetadata(defaultValue));
}
/// <summary>
/// 注册属性
/// public static readonly DependencyProperty Property = Utility.Property<T,T>(string,T);
/// </summary>
/// <typeparam name="thisType"></typeparam>
/// <typeparam name="propertyType"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
public static DependencyProperty Property<thisType, propertyType>(string name)
{
return DependencyProperty.Register(name.Replace("Property", ""), typeof(propertyType), typeof(thisType));
}
/// <summary>
/// 注册事件
/// public static readonly RoutedEvent NameRoutedEvent = Utility.RoutedEvent<T,T>(string,T);
/// public event EventHandler Name { add { AddHandler(EventHandler, value); } remove { RemoveHandler(EventHandler, value); } }
/// </summary>
/// <typeparam name="thisType"></typeparam>
/// <typeparam name="propertyType"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
public static RoutedEvent RoutedEvent<thisType, propertyType>(string name)
{
return EventManager.RegisterRoutedEvent(name.Replace("Event", ""), RoutingStrategy.Bubble, typeof(propertyType), typeof(thisType));
}
}
再写一个自定义的button类
class MyButton : Button
{
public static readonly DependencyProperty ResIdProperty = ElementBase.Property<MyButton, string>("ResIdProperty", "");
public string ResId
{
get
{
return GetValue(ResIdProperty).ToString();
}
set
{
SetValue(ResIdProperty, value);
}
}
}
这里就是定义了一个附件属性,
在看我的界面,可以直接绑定的哦
在代码里面可以直接使用的