我需要创建一个自定义属性而不是使用
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
</Style>
我喜欢像 Rectangle 这样的东西并为其分配一个 ID,这样当它被拖放到 Canvas 上时我可以检索它的 ID。
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
**<Setter Property="ID" Value="1234567890-ABC"/>**
</Style>
我如何定义该自定义属性?
问候, 阿米特
请您参考如下方法:
在单独的类中定义自定义附加属性:
public class Prop : DependencyObject
{
public static readonly DependencyProperty IDProperty =
DependencyProperty.RegisterAttached("ID", typeof(string), typeof(Prop), new PropertyMetadata(null));
public static void SetID(UIElement element, string value)
{
element.SetValue(IDProperty, value);
}
public static string GetID(UIElement element)
{
return (string)element.GetValue(IDProperty);
}
}
然后你可以使用这个:
<Setter Property="local:Prop.ID" Value="1234567890-ABC"/>
local 必须在 XAML 的根元素中定义,大致如下:
xmlns:local="clr-namespace:AttPropTest"
其中 AttPropTest 是程序集的命名空间。
在代码中,您可以使用Prop.GetID(myRect) 确定ID。
