【问题标题】:WPF: XAML property declarations not being set via Setters?WPF:XAML 属性声明不是通过 Setter 设置的?
【发布时间】:2011-04-19 15:53:15
【问题描述】:

我有一个 WPF 应用程序,我在其中使用我想通过 XAML 声明设置的代码隐藏中的依赖属性。

例如

<l:SelectControl StateType="A" Text="Hello"/>

所以在这个例子中,我有一个名为SelectControlUserControl,它有一个名为StateType 的属性,它在它的setter 中操纵其他一些属性。

为了帮助说明问题,我在示例中添加了另一个名为 Text 的属性,请继续阅读,我将进一步解释。

代码隐藏摘录...

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(String), typeof(SelectControl));

public String Text
{
  get { return (String)GetValue(TextProperty); }
  set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty StateTypeProperty = DependencyProperty.Register("StateType", typeof(String), typeof(SelectControl));

public String StateType
{
  get { return (String)GetValue(StateTypeProperty) }
  set
    {
      switch (value)
      {
        case "A":
          AnotherPropertyBoolean = true;
          break;
        case "B":
          AnotherPropertyBoolean = false;
          break;
       default:
         // this is only an example... 
      }
   }
}

现在,如果我在设置器上设置断点(StateTypeText),结果证明它从未执行过。

但是为Text 声明的值,即“Hello”出现在它的数据绑定TextBox 中,当然我将另一个文本控件绑定到StateType 的值我也可以看到。

有人知道发生了什么吗?

【问题讨论】:

    标签: wpf xaml dependency-properties setter


    【解决方案1】:

    依赖属性的“CLR-wrappers”只有在通过代码完成时才会被调用。 XAML 取决于 DependencyProperty.Register(...) 调用中指定的名称。因此,不要像上面那样为您的依赖属性“扩展”setter 的逻辑,只需将您的自定义逻辑放在 PropertyChangedCallback 函数中。

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多