I have a UserControl c:MenuButtons with an ItemsControl and the ItemTemplate is a DataTemplate with a RadioButton.

In the main wpf window I use the UserControl like this:

<c:MenuButtons x:Name="MenuProjects"
               SelectionChanged="{Binding d:MenuClick}"
               Height="35"
               MenuItems="{Binding Source={x:Static d:Main.Projects}}" />

I would like to have the Checked event of the RadioButton to bubble up via the UserControl to the MenuClick handler in the Main window code-behind and handle it there. This is a view-only thing so I do not use ICommand or model-patterns here.

The RadioButton Checked event is a RoutedEventHandler, so is SelectionChanged in c:MenuButtons and also MenuClick in my main window code-behind.

I cannot get it to work.

In the class MenuButtons I have the following code:

RoutedEventHandler handler;
public event RoutedEventHandler SelectionChanged
  {
     add { handler += value; }
     remove { handler -= value; }
  }

but the add is not entered despite the data-binding. Why not?

And: suppose it would be bound, how should I declare the binding in the DataTemplate?
I tried Checked="{Binding ElementName=root, Path=SelectionChanged}" which gives a XamlParseException on this particular attempt of binding (Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'.)

It turns out to be straightforward:
In the class MenuButtons you get:

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);
}

In the xaml of the UserControl you add:

<RadioButton Checked="RadioButton_Checked"

And in the main form you have:

 <c:MenuButtons SelectionChanged="MenuProjects_SelectionChanged"

There luckily e.OriginalSource gives the information for handling the event.

有帮助吗?

解决方案

You should check those links out:

http://msdn.microsoft.com/en-us/library/ms752288.aspx

And also this:

http://msdn.microsoft.com/en-us/library/ms742806.aspx

The tutorials will show you how to create routed events and how to subscribe them properly to elements.

Btw, add { handler += value; } is wrong.

This is how you should write it : add { this.AddHandler(MyRoutedEvent...); }

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top