C# 如何创建自定义属性?
我需要创建一个自定义属性,而不是使用C# 如何创建自定义属性?,c#,wpf,xaml,C#,Wpf,Xaml,我需要创建一个自定义属性,而不是使用 <Style x:Key="ABC" TargetType="Rectangle"> <Setter Property="Fill" Value="Red"/> </Style> 我喜欢有一个类似矩形的东西,并给它分配一个ID,这样以后当它被放到画布上时,我可以检索它的ID <Style x:Key="ABC" TargetType="Rectangle"> <Setter Prop
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
</Style>
我喜欢有一个类似矩形的东西,并给它分配一个ID,这样以后当它被放到画布上时,我可以检索它的ID
<Style x:Key="ABC" TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
**<Setter Property="ID" Value="1234567890-ABC"/>**
</Style>
****
如何定义该自定义属性
问候,,
Amit在单独的类中定义自定义附加属性:
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"/>
其中AttPropTest
是程序集的命名空间
在代码中,您可以使用
Prop.GetID(myRect)
在单独的类中定义自定义附加属性来确定ID:
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"/>
其中AttPropTest
是程序集的命名空间
在代码中,您可以使用
Prop.GetID(myRect)
确定ID是否要定义另一个类,如矩形,然后在其上定义属性?使用Tag
属性或查看是否要定义另一个类,如矩形,然后在其上定义属性?使用Tag
属性或查看Hi Fmunkert,这是一个很好的示例,所以我遵循了所有的步骤,但我猜这里缺少了一些东西,因为当我运行它时,我得到一个错误,因为(在XAML中)**无法将属性“Property”中的值转换为类型为“System.Windows.dependencProperty”的对象**您好,Fmunkert,这是一个很好的示例,所以我遵循了所有步骤,但我想我在这里遗漏了一些东西,因为当我运行它时,我得到一个错误,因为(在XAML中)**无法将属性“Property”中的值转换为类型为“System.Windows.dependencProperty”的对象**