我有一个UserControl
c:MenuButtons
与 ItemsControl
和 ItemTemplate
是 DataTemplate
与 RadioButton
.
在 wpf 主窗口中,我使用 UserControl
像这样:
<c:MenuButtons x:Name="MenuProjects"
SelectionChanged="{Binding d:MenuClick}"
Height="35"
MenuItems="{Binding Source={x:Static d:Main.Projects}}" />
我想要Checked
事件RadioButton
通过 UserControl
冒泡到MenuClick
主窗口代码隐藏中的处理程序并在那里处理它。这是一个仅供查看的东西,所以我不使用 ICommand
或此处的模型模式。
RadioButton
Checked
事件是 RoutedEventHandler
,SelectionChanged
也是如此在c:MenuButtons
还有MenuClick
在我的主窗口代码隐藏中。
我无法让它工作。
在 MenuButtons 类中,我有以下代码:
RoutedEventHandler handler;
public event RoutedEventHandler SelectionChanged
{
add { handler += value; }
remove { handler -= value; }
}
但是尽管有数据绑定(bind),但添加并未输入。为什么不呢?
并且:假设它是绑定(bind)的,我应该如何在 DataTemplate 中声明绑定(bind)?
我试过Checked="{Binding ElementName=root, Path=SelectionChanged}"
在此特定的绑定(bind)尝试上给出 XamlParseException(无法将“System.Reflection.RuntimeEventInfo”类型的对象强制转换为“System.Reflection.MethodInfo”类型。)
事实证明这很简单:
在 MenuButtons 类中你得到:
public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MenuButtons));
public event RoutedEventHandler SelectionChanged
{
add { AddHandler(SelectionChangedEvent, value); }
remove { RemoveHandler(SelectionChangedEvent, value); }
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
RoutedEventArgs eventargs = new RoutedEventArgs(MenuButtons.SelectionChangedEvent);
RaiseEvent(eventargs);
}
在 UserControl 的 xaml 中添加:
<RadioButton Checked="RadioButton_Checked"
在主窗体中,您有:
<c:MenuButtons SelectionChanged="MenuProjects_SelectionChanged"
幸运的是有e.OriginalSource
给出处理事件的信息。
最佳答案
您应该检查这些链接:
http://msdn.microsoft.com/en-us/library/ms752288.aspx
还有这个:
http://msdn.microsoft.com/en-us/library/ms742806.aspx
教程将向您展示如何创建路由事件以及如何将它们正确订阅到元素。
顺便说一句,add { handler += value; }
是错误的。
你应该这样写: add { this.AddHandler(MyRoulatedEvent...);
}
关于wpf - 如何将 RoutedEventHandler 正确传递给 UserControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19545694/