开发者

WPF Creating a Command Library

New to WPF/XAML and looking to build a Command library for my application. Current version of my application is "flat" meaning all the code behind resides in my MainWindow.cs file. I've decided to separate things out into User Controls and all the UI part so far works great but....

I'm having trouble binding my commands to things now that I've done this. To make it simple I created a new WPF project, added my Menu control (Controls\Menu.xaml) and referenced this in my MainWindow开发者_如何学JAVA.xaml. Now, I've gone ahead and added a CommandLibrary class and can't seem to get anything working. Here is my File -> New command code:

public static class MyAppCommands
{

    private static RoutedUICommand _NewItem;

    static MyAppCommands()
    {
        _NewItem = new RoutedUICommand("Create a new project", "NewItem", typeof(MyAppCommands));  
    }

    public static RoutedUICommand NewItem
    {
        get { return _NewItem; }
    }

    private string filePath = null;
    private bool dataChanged = false;

    public static void NewItem_Executed(object sender, ExecutedRoutedEventArgs e)
    {

        if (dataChanged)
        {
            string sf = SaveFirst();
            if (sf != "Cancel")
            {
                ClearState();
            }
        }
        else
        {
            ClearState();
        }
    }

    public static void NewItem_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    public static void BindCommandsToWindow(Window window)
    {
        window.CommandBindings.Add(new CommandBinding(NewItem, NewItem_Executed, NewItem_CanExecute));

    }

Where do I put the below in my class as a lot of my command will be using them...?

private string filePath = null;
private bool dataChanged = false;

Many Thanks!


I think you could benefit from setting up some design patterns like MVC or MVVM.

Check out these frameworks:

  • Caliburn (my favorite)
  • Prism

You can also follow MVC or MVVM just using a couple small helper classes, check out ariticles around the web, like this one MVVM.

Check this if you want a light-weight framework: MVVM Foundation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜