简体   繁体   English

如何创建自定义属性?

[英]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.

相关问题 如何创建具有多个属性依赖项的自定义验证 - How to create custom validation with multiple property dependencies 如何为我的媒体资源创建自定义事件 - how to create custom event for my property 更改属性后如何创建自定义事件? - How to create a custom event when a property is changed? 如何在自定义可绑定属性上创建与Intellisense兼容的枚举 - How to create Intellisense compatible enum on custom bindable property 如何使用EWS创建扩展(自定义)属性? - How can I create an Extended (custom) Property with EWS? 如何在WPF中创建具有依赖项属性的数字文本框自定义控件? - How to create numeric Textbox Custom Control with dependency Property in WPF? 如何创建自定义属性,例如在C#中的按钮上添加图像? - How to create a custom property like adding image on a button in c#? 如何在C#Win中创建DataGridViewTextBoxColumn的自定义属性。 形成 - How to create custom property of DataGridViewTextBoxColumn in c# win. form WPF控件模板 - 如何创建自定义属性? - WPF Control Templating - How do I create a custom property? 如何在Linq-to-SQL实体类中创建自定义属性? - How to create a custom property in a Linq-to-SQL entity class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM