Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

WPF: XAML property declarations not being set via Setters?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...