【问题标题】:WPF UserControl with a url as dependencyproperty带有 url 作为依赖属性的 WPF UserControl
【发布时间】:2017-07-17 10:03:04
【问题描述】:

我正在创建一个 wpf 用户控件,它基本上是一个应该打开文档的按钮。我想创建它,以便任何人都可以将此文档的 url 放在 xaml 中。这可能吗?

编辑:我添加了一个依赖属性来存储 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)));

【问题讨论】:

    标签: wpf xaml


    【解决方案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://...." />
    

    【讨论】:

      猜你喜欢
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多