我正在创建一个wpf usercontrol,它基本上是一个应该打开文档的按钮。我想创建它,以便任何人都可以将此文档的URL放在xaml中。这可能吗?
编辑:我添加了一个dependencyproperty来存储url,但是每当我尝试构建它时它都会抛出异常。 xaml看起来像这样:
<controls:HelpButton WidthAndHeight="40" HelpDocUrl="somUrl"/>
我的属性背后的代码如下:
public string HelpDocUrl
{
get { return (string)GetValue(HelpDocUrlProperty); }
set { SetValue(HelpDocUrlProperty, value); }
}
public static readonly DependencyProperty HelpDocUrlProperty = DependencyProperty.Register("HelpDocUrl", typeof(string), typeof(HelpButton), new PropertyMetadata(default(string)));
答案 0 :(得分:1)
添加UserControl
的代码隐藏类的依赖项属性:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty UrlProperty =
DependencyProperty.Register("Url", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public string Url
{
get { return (string)GetValue(UrlProperty); }
set { SetValue(UrlProperty, value); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string url = Url;
//...
}
}
...您的控件的任何消费者都可以照常设置:
<local:UserControl1 Url="http://...." />