要设置自定义属性,首先需要在 XAML 文件中定义该属性,然后在代码中为该属性赋值。以下是一个简单的示例:
- 在 XAML 文件中定义自定义属性:
在这个示例中,我们定义了一个名为 MyCustomProperty
的自定义属性,并将其赋值为 “Hello, World!”。
- 在代码中为自定义属性赋值:
using System.Windows;
namespace CustomPropertyDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string customPropertyValue = https://www.yisu.com/ask/CustomProperties.GetMyCustomProperty(btn);"MyCustomProperty", typeof(string), typeof(CustomProperties), new PropertyMetadata(""));
public static void SetMyCustomProperty(UIElement element, string value)
{
element.SetValue(MyCustomPropertyProperty, value);
}
public static string GetMyCustomProperty(UIElement element)
{
return (string)element.GetValue(MyCustomPropertyProperty);
}
}
}
在代码中,我们定义了一个名为 MyCustomPropertyProperty
的依赖属性,然后通过 SetMyCustomProperty
方法为按钮赋予了自定义属性值。在窗口初始化时,我们通过 GetMyCustomProperty
方法获取按钮的自定义属性值,并弹出一个消息框显示该值。
这样,我们就成功地设置了一个自定义属性并为其赋值。