Custom Mark-up Extensions return RoutedEvents
I'm trying to create a generalized event for my Close buttons, where they have to close the window but before that set focus to the owner window. I don't want to have an event for every file for that, because that'd be pretty unpractical since I have 30+ windows in my application. (So if I wanted to change that behavior, i'd have to change on 30 files everytime)
I'm not sure if that's the correct approach, but I tried making a MarkUp Extension which returns a delegate(object sender, RoutedEventArgs e) Here is the code:
delegate void RoutedDelegate(object sender, RoutedEventArgs e);
[MarkupExtensionReturnType(typeof(RoutedEvent))]
public class CloseWindowExtension : MarkupExtension
{
    Window 开发者_StackOverflowwin = null;
    public Window Win
    {
        get { return this.win; }
        set { this.win = value; }
    }
    public CloseWindowExtension(Window win)
        : base()
    {
        this.win = win;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (win == null)
        {
            throw new InvalidOperationException("The window must be specified!");
        }
        return new RoutedDelegate(delegate(object sender, RoutedEventArgs e)
        {
            Extensions.FocusClose(win);
        });
    }
}
The FocusClose method gets a window, closes it, but sets focus to its owner before. But I can't make it work. When i set my button in the xaml,
Button Click="{e:CloseWindow {Binding win}}"
(win is my Window name), I get the error message:
Click="{e:CloseWindow {Binding win}}" is not valid. '{e:CloseWindow {Binding win}}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid. Line 28 Position 17.
Am I doing something wrong? Is this the best approach or do I have another options? Thanks in advance!
Clark
You can't use a markup extension to set an event handler. Instead, you can use an attached behavior, which allows you to bind a command to an event.
See this article by Marlon Grech for details
.NET 4.5+ supports markup extensions for events, so you can implement what you wanted now :)
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论