您可以使用Tag
属性,但通用标签是 winforms 时代的遗留物。在这里阅读。我不喜欢标签是它们没有类型,这意味着要从中读取,并且它们没有有意义的名称。另一种选择是:
附件属性
很难写,幸运的是 VS 有一个片段类型propa
和按标签。
所以:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Shapes;
namespace SO_AttachmentProperty
{
public sealed class EllipseAttachments
{
#region Field1
public static int GetField1(DependencyObject obj)
{
return (int)obj.GetValue(Field1Property);
}
public static void SetField1(DependencyObject obj, int value)
{
obj.SetValue(Field1Property, value);
}
// Using a DependencyProperty as the backing store for Field1. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Field1Property =
DependencyProperty.RegisterAttached("Field1", typeof(int), typeof(EllipseAttachments), new UIPropertyMetadata(0));
#endregion
#region Field2
public static int GetField2(DependencyObject obj)
{
return (int)obj.GetValue(Field2Property);
}
public static void SetField2(DependencyObject obj, int value)
{
obj.SetValue(Field2Property, value);
}
// Using a DependencyProperty as the backing store for Field2. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Field2Property =
DependencyProperty.RegisterAttached("Field2", typeof(int), typeof(EllipseAttachments), new UIPropertyMetadata(0));
#endregion
}
}
然后像这样使用属性:
在代码中
var ellipse = new Ellipse();
//write
EllipseAttachments.SetField1(ellipse, 123);
EllipseAttachments.SetField2(ellipse, 456);
//read
var f1 = EllipseAttachments.GetField1(ellipse);
var f2 = EllipseAttachments.GetField2(ellipse);
附件属性在 xaml 中有自己的
注意本地命名空间。
<Window x:Class="SO_AttachmentProperty.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SO_AttachmentProperty"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Ellipse local:EllipseAttachments.Field1="789" local:EllipseAttachments.Field2="67"/>
</Grid>
</Window>