【问题标题】:Is there a way to simplify setup of dependency properties in WPF and Silverlight?有没有办法简化 WPF 和 Silverlight 中依赖属性的设置?
【发布时间】:2011-04-20 04:41:47
【问题描述】:

我有一个基本的 WPF/Silverlight 用户控件代码,其中包含一个标签,我想设置来自使用该控件的代码的值。有没有办法简化定义依赖属性和相关事件的要求?对于看似简单的编码任务(属性、方法和相关接线)来说,这似乎非常嘈杂。

    private static DependencyProperty CountProperty;

    public MyWpfUserControl()
    {
        InitializeComponent();
        PropertyChangedCallback countChangedCallback = CountChanged;
        var metaData = new PropertyMetadata(countChangedCallback);
        CountProperty = DependencyProperty.Register("Count", typeof (int), typeof (MyWpfUserControl), metaData);
    }

    public int ItemsCount
    {
        get { return (int) GetValue(CountProperty); }
        set { SetValue(CountProperty, value); }
    }

    private void CountChanged(DependencyObject property,
                              DependencyPropertyChangedEventArgs args)
    {
        // Set the value of another control to this property
        label1.Content = ItemsCount;
    }

【问题讨论】:

  • 键入“propdp”并在代码的任意位置按两次 Tab 键。在我看来,CountChanged 属性必须是静态的。

标签: wpf silverlight wpf-controls


【解决方案1】:

你说得对,依赖属性是丑陋且笨拙的。实际上,在您上面的代码示例中,甚至存在错误!你需要给医生打电话——WPF博士!

这里是 WPF 博士的 sn-ps,用于您想要的所有依赖属性风格:

他的网站上也有视频显示他使用它们。老实说,我自己不使用它们,但我一直想尝试一下。我确实使用内置的 sn-ps。

【讨论】:

  • 谢谢。我会检查这些。您能否指出您一段时间以来发现的错误,以便我可以在示例中记录它们?
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多