Call events or methods located in a Class from XAML

前端 未结 2 1924
名媛妹妹
名媛妹妹 2021-01-27 03:54

Hi i am trying if it\'s possible having an Event like TextChanged (of a TextBox) located in another place independent of the Window CodeBehind (like a Class).

What i am

2条回答
  •  孤城傲影
    2021-01-27 04:25

    Edit: Disregard this unless you want to subclass TextBox to execute a command on TextChanged. (I think the trigger-method is to be preferred.)

    But it's possible making reference in ResourceDictionaries to an Event located in the CodeBehind of the Window where that control belongs? Imagine the following, instead of we are setting an Event to a Control in the XAML, we do that in the dictionary in a style. That is possible?

    I would suggest Commands for this; define a RoutedCommand somewhere:

    public static class Commands
    {
        public static RoutedCommand DoStuff = new RoutedCommand();
    }
    

    Set it to the button in the dictionary:

    And create a command binding:

    
        
            
        
        
    
    
    private void DoStuff_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        // What happens if the command is executed, in this case the Button-click can
        // cause this to happen, you can also create KeyBindings which can execute
        // commands for example.
        MessageBox.Show("!");
    }
    private void DoStuff_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true; //No condition: Command can always be executed
    
        // e.CanExecute = false causes the button to be disabled.
    }
    

提交回复
热议问题