MVVM Madness: Commands

后端 未结 7 1081
星月不相逢
星月不相逢 2021-01-30 01:38

I like MVVM. I don\'t love it, but like it. Most of it makes sense. But, I keep reading articles that encourage you to write a lot of code so that you can write XAML and don\'t

相关标签:
7条回答
  • 2021-01-30 02:12

    What @JP describes in the original question and @Heinzi mentions in is answer is a pragmatic approach to handling difficult commands. Using a tiny bit of event handling code in the code behind comes in especially handy when you need to do a little UI work before invoking the command.

    Consider the classic case of the OpenFileDialog. It's much easier to use a click event on the button, display the dialog, and then send the results to a command on your ViewModel than to adopt any of the complicated messaging routines used by the MVVM toolkits.

    In your XAML:

    <Button DockPanel.Dock="Left" Click="AttachFilesClicked">Attach files</Button>
    

    In your code behind:

        private void AttachFilesClicked(object sender, System.Windows.RoutedEventArgs e)
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".txt"; // Default file extension
            dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
    
            // Show open file dialog box
            bool? result = dlg.ShowDialog();
    
            // Process open file dialog box results
            if (result == true)
            {
                string filename = dlg.FileName;
    
                // Invoke the command.
                MyViewModel myViewModel = (MyViewModel)DataContext;
                if (myViewModel .AttachFilesCommand.CanExecute(filename))
                {
                    noteViewModel.AttachFilesCommand.Execute(filename);  
                }
            }
        }
    

    Computer programming is inflexible. We programmers have to be flexible to order to deal with that.

    0 讨论(0)
提交回复
热议问题