如何将自定义属性添加到WPF用户控件
本文关键字:WPF 用户 控件 添加 自定义属性 | 更新日期: 2023-09-27 18:22:10
我有自己的用户控制,包括一些按钮等。
我用这个代码把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页面时,系统会抛出一个异常,如"";成员"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",然后键入TabTab,则可以在Visual Studio中找到此代码段。您需要填写DependencyProperty的类型、DependencyProperties的名称、包含它的类以及该DependencyProperty的默认值(在我的示例中,我将false
作为默认值)。
您可能没有正确声明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页面中找到进一步的帮助。