[英]How to create a custom property?
I need to create a custom property meaning rather using 我需要创建一个自定义属性,而不是使用
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
</Style>
I like to have something like Rectangle and assign it an ID so later when it is dropped on Canvas I can retrieve its ID. 我喜欢像Rectangle这样的东西,并为它分配一个ID,以便稍后在Canvas上删除它我可以检索它的ID。
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
**<Setter Property="ID" Value="1234567890-ABC"/>**
</Style>
How can I define that custom property? 如何定义该自定义属性?
Regards, Amit 此致,阿米特
Define a custom attached property in a separate class: 在单独的类中定义自定义附加属性:
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);
}
}
Then you can use this: 然后你可以使用这个:
<Setter Property="local:Prop.ID" Value="1234567890-ABC"/>
local
must be defined in the root element of your XAML appromimately like this: local
必须在XAML appromimately这样的根元素来定义:
xmlns:local="clr-namespace:AttPropTest"
where AttPropTest
is the namespace of the assembly. 其中AttPropTest
是程序集的命名空间。
In code, you can determine the ID with Prop.GetID(myRect)
. 在代码中,您可以使用Prop.GetID(myRect)
确定ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.