如何将自定义属性添加到WPF用户控件
我有自己的用户控件,包括几个按钮等。
我使用这段代码将UC带到屏幕上。
我已将两个属性(如Property1和Property2)添加到XXXX用户控件。 并改变了我的代码
当我将这2个参数添加到XAML页面时,系统会抛出一个exception,例如“成员’Property1’无法识别或无法访问”
这是我的UC代码。
public partial class XXXX : UserControl { public event EventHandler CloseClicked; public event EventHandler MinimizeClicked; //public bool ShowMinimize { get; set; } public static DependencyProperty Property1Property; public static DependencyProperty Property2Property; public XXXX() { InitializeComponent(); } static XXXX() { Property1Property = DependencyProperty.Register("Property1", typeof(bool), typeof(XXXX)); Property2Property = DependencyProperty.Register("Property2", typeof(bool), typeof(XXXX)); } public bool Property1 { get { return (bool)base.GetValue(Property1Property); } set { base.SetValue(Property1Property, value); } } public bool Property2 { get { return (bool)base.GetValue(Property2Property); } set { base.SetValue(Property2Property, value); } } }
你可以帮我做这件事吗? 非常感谢!
您可以将此声明用于DependencyProperties:
public bool Property1 { get { return ( bool ) GetValue( Property1Property ); } set { SetValue( Property1Property, value ); } } // Using a DependencyProperty as the backing store for Property1. // This enables animation, styling, binding, etc... public static readonly DependencyProperty Property1Property = DependencyProperty.Register( "Property1", typeof( bool ), typeof( XXXX ), new PropertyMetadata( false ) );
如果您键入“propdp”,然后选择Tab Tab ,则可以在Visual Studio中找到此代码段。 您需要填充DependencyProperty的类型,DependencyProperty的名称,包含它的类以及该DependencyProperty的默认值(在我的示例中,我将false
为默认值)。
您可能没有正确声明DependencyProperty
。 您可以在MSDN的依赖项属性概述页面中找到有关如何创建DependencyProperty
的完整详细信息,但简而言之,它们看起来像这样(取自链接页面):
public static readonly DependencyProperty IsSpinningProperty = DependencyProperty.Register( "IsSpinning", typeof(Boolean), ... ); public bool IsSpinning { get { return (bool)GetValue(IsSpinningProperty); } set { SetValue(IsSpinningProperty, value); } }
您可以在MSDN上的DependencyProperty Class页面中找到更多帮助。