WPF:XAML属性声明未通过设置器设置吗? [英] WPF: XAML property declarations not being set via Setters?
问题描述
我有一个WPF应用程序,在其中我要通过XAML声明进行设置的代码隐藏使用依赖项属性。
例如
< l:SelectControl StateType = A Text = Hello />
因此在此示例中,我有 UserControl
称为 SelectControl
,它具有名为 StateType
的属性,该属性可以操纵其设置程序中的其他一些属性。
为帮助说明问题,在示例中放置了另一个名为 Text
的属性,请继续阅读,我将作进一步解释。 / p>
代码摘要摘录...
公共静态只读DependencyProperty TextProperty = DependencyProperty .Register( Text,typeof(String),typeof(SelectControl));
public String Text
{
get {return(String)GetValue(TextProperty); }
set {SetValue(TextProperty,value); }
}
公共静态只读DependencyProperty StateTypeProperty = DependencyProperty.Register( StateType,typeof(String),typeof(SelectControl));
public String StateType
{
get {return(String)GetValue(StateTypeProperty)}
set
{
switch(value)
{
case A:
AnotherPropertyBoolean = true;
休息时间;
case B:
AnotherPropertyBoolean = false;
休息时间;
默认值:
//这只是一个示例...
}
}
}
现在,如果我在设置器上设置了一个断点(对于 StateType
或 Text
),结果证明它从未执行过。
但是为 Text
声明的值,即在数据绑定的 TextBox
中出现 Hello,当然,我将另一个文本控件绑定到 StateType
的值上我也可以看到。
有人知道发生了什么吗?
仅通过代码完成时,才会调用依赖项属性的 CLR包装器。 XAML取决于DependencyProperty.Register(...)调用中指定的名称。因此,不要像上面那样扩展您的依赖项属性的设置器的逻辑,只需将自定义逻辑放在 PropertyChangedCallback 函数。
I have a WPF application where I'm using dependency properties in codebehind which I want to set via XAML declarations.
e.g.
<l:SelectControl StateType="A" Text="Hello"/>
So in this example I have a UserControl
called SelectControl
, which has a property called StateType
which manipulate some other properties in it's setter.
To help illustrate the problem, I've put another property called Text
in the example, read on and I'll explain further.
Codebehind excerpt...
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...
}
}
}
Now, if I set a breakpoint on the setter (for either StateType
or Text
), it turns out it's never executed.
However values declared for Text
, i.e. "Hello" appears in it's data bound TextBox
, and of course it I bind another text control to StateType
's value I can see that too.
Does anyone know what's happening?
The "CLR-wrappers" for dependency properties only get called when done through code. XAML depends on the name specified in the DependencyProperty.Register(...) call. So, instead of "extending" the logic of the setter for your dependency property like you did above, just put your custom logic in a PropertyChangedCallback function.
这篇关于WPF:XAML属性声明未通过设置器设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!