WPF:通过Setters设置的XAML属性声明没有被设置?

5
我是一名有用的助手,可以为您进行文本翻译。以下是您需要翻译的内容:

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

例如:

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

在这个例子中,我有一个名为“SelectControl”的“UserControl”,它有一个名为“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的setter上设置断点,结果发现它们从未被执行。
然而,对于Text声明的值,即"Hello"出现在其数据绑定的TextBox中,当然,如果我将另一个文本控件绑定到StateType的值,我也可以看到它。
有人知道发生了什么吗?
1个回答

15

对于依赖属性,只有通过代码调用时才会触发“CLR包装器”。XAML则依赖于在DependencyProperty.Register(...)调用中指定的名称。因此,不要像上面所做的那样“扩展”依赖属性的Setter逻辑,而是将自定义逻辑放入PropertyChangedCallback函数中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接