Is it possible to set code behind a resource dictionary in WPF for event handling?

前端 未结 4 1806
孤城傲影
孤城傲影 2020-11-22 10:49

Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button clic

4条回答
  •  长发绾君心
    2020-11-22 10:54

    I disagree with "ageektrapped"... using the method of a partial class is not a good practice. What would be the purpose of separating the Dictionary from the page then?

    From a code-behind, you can access a x:Name element by using:

    Button myButton = this.GetTemplateChild("ButtonName") as Button;
    if(myButton != null){
       ...
    }
    

    You can do this in the OnApplyTemplate method if you want to hookup to controls when your custom control loads. OnApplyTemplate needs to be overridden to do this. This is a common practice and allows your style to stay disconnected from the control. (The style should not depend on the control, but the control should depend on having a style).

提交回复
热议问题