0
votes

I am little new to Command binding so this might be a trivial question to many. I know that we can add Command bindings in xaml of a window and give its correspondng property in viewmodel. This viewmodel will be given to the DataContext of the window. Something like the following

--app.xaml.cs

mainWindow.DataContext = viewModel;

-- xaml

lt;Button Grid.Row="1" HorizontalAlignment="Right" Margin="0,3,18,3" Name="button1" Width="110" 
                Command="{Binding LoadCommand}">_Load</Button>

-- viewmodel

/// <summary>
        /// Gets the load command.
        /// </summary>
        /// <value>The load command.</value>
        public ICommand LoadCommand
        {
            get
            {
                if (m_LoadCommand == null)
                {
                    m_LoadCommand = new RelayCommand(param => CanLoad(), param => Load());
                }

                return m_LoadCommand;
            }
        }

Here the relaycommand is a class which implements ICommand interface. CanLoad() and Load() are the methods which will get executed for canexecute and execute action of the relaycommand respectively. This is the click event of the button which is handled.

I have a user control which has a custom routedevent registered in it and the user control is then used on a window. I am currently adding the event handler explicitly in code.

//hook up event listeners on the actual UserControl instance
            this.ucCustomEvent1.CustomClick += new RoutedEventHandler(ucCustomEvent_CustomClick);
            //hook up event listeners on the main window (Window1)
            this.AddHandler(UserControlThatCreatesEvent.CustomClickEvent, new RoutedEventHandler(ucCustomEvent_CustomClick));

I dont want to hook up the routedevent explicitly in code but in the xaml in the similar way as in the button example. I have uploaded the working sample code here for your perusal.

1

1 Answers

2
votes

I'm not sure I fully understand your question but I hope one of my answers below helps you out.

To attach a "direct" event handler in XAML, just do the following:

<c:MyUserControl x:Name="uc1" CustomClick="uc1_CustomClickHandler"/>

To hook up a handler for the (routed) event of one element (e.g. the CustomClick event in your example) to another element (e.g. the parent window):

<Window c:MyUserControl.CustomClick="ucCustomEvent_CustomClick"/>

Now, if you want to tie up an event in your UI to a Command in your ViewModel, you will need attached behaviors to do that. There are lots of frameworks around featuring different implementations of this. Here's one you can try out: http://sachabarber.net/?p=514. It will allow you to do something like the following in your code:

 <c:MyUserControl local:CommandBehavior.RoutedEventName="MyCustomClick"
                  local:CommandBehavior.TheCommandToRun="{Binding MyViewModelCommand}"/>

Hope this helps.