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

cKN*_*Net 17 c# wpf

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

我使用这段代码将UC带到屏幕上.

<AppUI:XXXX x:Name="ucStaticBtns" HorizontalAlignment="Left" Margin="484,0,0,0" VerticalAlignment="Top" Width="68" />
Run Code Online (Sandbox Code Playgroud)

我已将两个属性(如Property1和Property2)添加到XXXX用户控件.并改变了我的代码

<AppUI:XXXX x:Name="ucStaticBtns" HorizontalAlignment="Left" Margin="484,0,0,0" VerticalAlignment="Top" Width="68" Property1="False" Property2="False"/>
Run Code Online (Sandbox Code Playgroud)

当我将这2个参数添加到XAML页面时,系统会抛出一个异常,例如"成员'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); }
        }
}
Run Code Online (Sandbox Code Playgroud)

你可以帮我这么做吗?非常感谢!

bsg*_*des 33

您可以将此声明用于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 ) 
      );
Run Code Online (Sandbox Code Playgroud)

如果您键入"propdp",则可以在Visual Studio中找到此代码段TabTab.您需要填充DependencyProperty的类型,DependencyProperty的名称,包含它的类以及该DependencyProperty的默认值(在我的示例中,我将其置false为默认值).

  • VS将生成的代码片段(通过`propdp`)适应我的修改的方式很神奇.你知道一个"备忘单"显示更多吗? (5认同)
  • 令我惊讶的是 XAML 没有办法做到这一点。我本以为 &lt;sys:Boolean x:Name="Property1" /&gt; 或类似的东西将是开发控件的更简洁的方式。 (2认同)