如何向WPF用户控件添加自定义属性

20

我有自己的用户控件,其中包括几个按钮等。

我使用此代码将该UC带到屏幕上。

<AppUI:XXXX x:Name="ucStaticBtns" HorizontalAlignment="Left" Margin="484,0,0,0" VerticalAlignment="Top" Width="68" />

我给XXXX用户控件添加了两个属性,比如Property1和Property2。然后修改了我的代码:

<AppUI:XXXX x:Name="ucStaticBtns" HorizontalAlignment="Left" Margin="484,0,0,0" VerticalAlignment="Top" Width="68" Property1="False" Property2="False"/>

当我将这两个参数添加到XAML页面中时,系统会抛出异常,如"The member 'Property1' is not recognized or is not accessible"

这是我的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); }
        }
}

你能帮我完成这个吗?非常感谢!

2个回答

47
你可以使用此声明来定义您的 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 ) 
      );

如果在Visual Studio中键入“propdp”,然后按 Tab Tab ,您将找到此代码片段。 您需要填写DependencyProperty的类型、DependencyProperty的名称、包含它的类和该DependencyProperty的默认值(在我的示例中,我将false作为默认值)。


9
使用“propdp”方式,VS如何调整生成的代码片段以适应我的修改,真是太神奇了。你知道是否有“速查表”展示更多相关信息吗? - Informagic
1
在苦苦挣扎了几天的数据上下文问题后,我退后一步,重新使用这个简单的例子开始。纯金。 - JKH
2
让我感到惊讶的是,XAML 没有一种方法来做到这一点。我本以为 <sys:Boolean x:Name="Property1" /> 或类似的方式会是开发控件更加清晰的方式。 - Alan Baljeu

2
您可能没有正确声明您的DependencyProperty。您可以在MSDN上的 Dependency Properties Overview页面找到有关如何创建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 页面中找到更多帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接