对于我的项目,我使用DependencyProperty
向我的控件添加附加属性。
它有效,但我希望在VisualStudio属性窗口中显示我的属性。
我没有创建任何UserControl
,因为我希望所有标准控件都具有此属性。
另外,我不想使用现有的Tag
属性,因为将来我会添加更多属性。
这可能吗?怎么做?
我的XAML:
<Window x:Class="Wpf_CustomPropertyTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Wpf_CustomPropertyTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button1" Content="Button 1" local:Extensions.MyTestProp="Hello 1!" Click="button_Click" HorizontalAlignment="Left" Height="39" Margin="36,36,0,0" VerticalAlignment="Top" Width="171" />
<Button x:Name="button2" Content="Button 2" local:Extensions.MyTestProp="Hello 2!" Click="button_Click" HorizontalAlignment="Left" Height="39" Margin="36,90,0,0" VerticalAlignment="Top" Width="171" />
</Grid>
</Window>
我的代码隐藏:
using System.Windows;
namespace Wpf_CustomPropertyTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Extensions.GetMyTestProp((UIElement)sender));
}
}
public class Extensions
{
public static readonly DependencyProperty MyTestPropProperty = DependencyProperty.RegisterAttached("MyTestProp", typeof(string), typeof(Extensions), new PropertyMetadata(default(string)));
public static void SetMyTestProp(UIElement element, string value)
{
element.SetValue(MyTestPropProperty, value);
}
public static string GetMyTestProp(UIElement element)
{
return (string)element.GetValue(MyTestPropProperty);
}
}
}