将用户控件的自定义路由事件添加到wpf中窗口的xaml

将用户控件的自定义路由事件添加到wpf中窗口的xaml,wpf,wpf-controls,Wpf,Wpf Controls,我对命令绑定并不陌生,所以这对许多人来说可能是一个微不足道的问题。我知道我们可以在窗口的xaml中添加命令绑定,并在viewmodel中给出相应的属性。此viewmodel将提供给窗口的DataContext。类似于下面的内容 --app.xaml.cs mainWindow.DataContext = viewModel; mainWindow.DataContext=viewModel; --xaml 书信电报;Button Grid.Row=“1”HorizontalAlignment=“

我对命令绑定并不陌生,所以这对许多人来说可能是一个微不足道的问题。我知道我们可以在窗口的xaml中添加命令绑定,并在viewmodel中给出相应的属性。此viewmodel将提供给窗口的DataContext。类似于下面的内容

--app.xaml.cs

mainWindow.DataContext = viewModel; mainWindow.DataContext=viewModel; --xaml

书信电报;Button Grid.Row=“1”HorizontalAlignment=“Right”Margin=“0,3,18,3”Name=“button1”Width=“110” Command=“{Binding LoadCommand}”>\u Load --视图模型

/// <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; } } /// ///获取load命令。 /// ///加载命令。 公共ICommand LoadCommand { 得到 { 如果(m_LoadCommand==null) { m_LoadCommand=new RelayCommand(param=>CanLoad(),param=>Load()); } 返回m_LoadCommand; } } 这里relaycommand是一个实现ICommand接口的类。CanLoad()和Load()是分别为relaycommand的canexecute和execute操作执行的方法。这是已处理的按钮的单击事件

我有一个用户控件,其中注册了一个自定义RouteEvent,然后在窗口上使用该用户控件。我目前正在代码中显式添加事件处理程序

//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)); //在实际的UserControl实例上连接事件侦听器 this.ucCustomEvent1.CustomClick+=新路由事件处理器(ucCustomEvent\u CustomClick); //在主窗口(Window1)上连接事件侦听器 this.AddHandler(UserControlThatCreatesEvent.CustomClickEvent,new RoutedEventHandler(ucCustomEvent\U CustomClick));
我不想在代码中显式地连接RouteEvent,而是以与button示例中类似的方式在xaml中连接RouteEvent。我已经上传了工作示例代码供您阅读。

我不确定我是否完全理解您的问题,但我希望下面的一个答案可以帮助您

要在XAML中附加“直接”事件处理程序,只需执行以下操作:

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

要将一个元素(例如示例中的CustomClick事件)的(路由)事件的处理程序连接到另一个元素(例如父窗口),请执行以下操作:


现在,如果您想将UI中的事件绑定到ViewModel中的命令,则需要附加行为来完成此操作。有很多框架都有不同的实现。这里有一个你可以试试的:。它将允许您在代码中执行以下操作:

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


希望这能有所帮助。

你好,Karmi,您的上一个代码工作正常。我真的想知道这是什么地方:CommandBehavior,但后来我知道这是一个类。还有一个问题,我如何将sender和RoutedEventArgs传递给MyViewModelCommand属性?嗯。。。这将有点棘手,需要对链接中的CommandBehavior类进行一些自定义。我想说的是,如果您使用的是MVVM模式,则可能不建议将sender和args传递给viewmodel命令。但无论如何,要做到这一点,我认为您需要修改CommandBehavior并在其中定义另一个附加属性,比如“CommandBehavior.PassEventInfo=true”。
<Window c:MyUserControl.CustomClick="ucCustomEvent_CustomClick"/>
 <c:MyUserControl local:CommandBehavior.RoutedEventName="MyCustomClick"
                  local:CommandBehavior.TheCommandToRun="{Binding MyViewModelCommand}"/>