在MVVM中为View提供一些命令

Sib*_*Guy 16 .net c# wpf mvvm

我们假设我有一些用户控制权.用户控件有一些子窗口.并且用户控制用户想要关闭某种类型的子窗口.用户控制代码中有一种方法:

public void CloseChildWindows(ChildWindowType type)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

但我无法调用此方法,因为我无法直接访问该视图.

我想到的另一个解决方案是以某种方式将用户控件ViewModel作为其属性之一公开(因此我可以绑定它并直接向ViewModel发出命令).但我不希望用户控制用户知道有关用户控件ViewModel的任何信息.

那么解决这个问题的正确方法是什么?

Mik*_*chs 41

我觉得我刚刚找到了一个相当不错的MVVM解决方案来解决这个问题.我写了一个暴露类型属性WindowType和布尔属性的行为Open.DataBinding后者允许ViewModel轻松打开和关闭窗口,而不需要了解View.

要爱的行为...... :)

在此输入图像描述

XAML:

<UserControl x:Class="WpfApplication1.OpenCloseWindowDemo"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.DataContext>
        <local:ViewModel />
    </UserControl.DataContext>
    <i:Interaction.Behaviors>
        <!-- TwoWay binding is necessary, otherwise after user closed a window directly, it cannot be opened again -->
        <local:OpenCloseWindowBehavior WindowType="local:BlackWindow" Open="{Binding BlackOpen, Mode=TwoWay}" />
        <local:OpenCloseWindowBehavior WindowType="local:YellowWindow" Open="{Binding YellowOpen, Mode=TwoWay}" />
        <local:OpenCloseWindowBehavior WindowType="local:PurpleWindow" Open="{Binding PurpleOpen, Mode=TwoWay}" />
    </i:Interaction.Behaviors>
    <UserControl.Resources>
        <Thickness x:Key="StdMargin">5</Thickness>
        <Style TargetType="Button" >
            <Setter Property="MinWidth" Value="60" />
            <Setter Property="Margin" Value="{StaticResource StdMargin}" />
        </Style>
        <Style TargetType="Border" >
            <Setter Property="Margin" Value="{StaticResource StdMargin}" />
        </Style>
    </UserControl.Resources>

    <Grid>
        <StackPanel>
            <StackPanel Orientation="Horizontal">
                <Border Background="Black" Width="30" />
                <Button Content="Open" Command="{Binding OpenBlackCommand}" CommandParameter="True" />
                <Button Content="Close" Command="{Binding OpenBlackCommand}" CommandParameter="False" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Border Background="Yellow" Width="30" />
                <Button Content="Open" Command="{Binding OpenYellowCommand}" CommandParameter="True" />
                <Button Content="Close" Command="{Binding OpenYellowCommand}" CommandParameter="False" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Border Background="Purple" Width="30" />
                <Button Content="Open" Command="{Binding OpenPurpleCommand}" CommandParameter="True" />
                <Button Content="Close" Command="{Binding OpenPurpleCommand}" CommandParameter="False" />
            </StackPanel>
        </StackPanel>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

YellowWindow(黑/紫色):

<Window x:Class="WpfApplication1.YellowWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="YellowWindow" Height="300" Width="300">
    <Grid Background="Yellow" />
</Window>
Run Code Online (Sandbox Code Playgroud)

ViewModel,ActionCommand:

using System;
using System.ComponentModel;
using System.Windows.Input;

namespace WpfApplication1
{
    public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private bool _blackOpen;
        public bool BlackOpen { get { return _blackOpen; } set { _blackOpen = value; OnPropertyChanged("BlackOpen"); } }

        private bool _yellowOpen;
        public bool YellowOpen { get { return _yellowOpen; } set { _yellowOpen = value; OnPropertyChanged("YellowOpen"); } }

        private bool _purpleOpen;
        public bool PurpleOpen { get { return _purpleOpen; } set { _purpleOpen = value; OnPropertyChanged("PurpleOpen"); } }

        public ICommand OpenBlackCommand { get; private set; }
        public ICommand OpenYellowCommand { get; private set; }
        public ICommand OpenPurpleCommand { get; private set; }


        public ViewModel()
        {
            this.OpenBlackCommand = new ActionCommand<bool>(OpenBlack);
            this.OpenYellowCommand = new ActionCommand<bool>(OpenYellow);
            this.OpenPurpleCommand = new ActionCommand<bool>(OpenPurple);
        }

        private void OpenBlack(bool open) { this.BlackOpen = open; }
        private void OpenYellow(bool open) { this.YellowOpen = open; }
        private void OpenPurple(bool open) { this.PurpleOpen = open; }

    }

    public class ActionCommand<T> : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private Action<T> _action;

        public ActionCommand(Action<T> action)
        {
            _action = action;
        }

        public bool CanExecute(object parameter) { return true; }

        public void Execute(object parameter)
        {
            if (_action != null)
            {
                var castParameter = (T)Convert.ChangeType(parameter, typeof(T));
                _action(castParameter);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

OpenCloseWindowBehavior:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace WpfApplication1
{
    public class OpenCloseWindowBehavior : Behavior<UserControl>
    {
        private Window _windowInstance;

        public Type WindowType { get { return (Type)GetValue(WindowTypeProperty); } set { SetValue(WindowTypeProperty, value); } }
        public static readonly DependencyProperty WindowTypeProperty = DependencyProperty.Register("WindowType", typeof(Type), typeof(OpenCloseWindowBehavior), new PropertyMetadata(null));

        public bool Open { get { return (bool)GetValue(OpenProperty); } set { SetValue(OpenProperty, value); } }
        public static readonly DependencyProperty OpenProperty = DependencyProperty.Register("Open", typeof(bool), typeof(OpenCloseWindowBehavior), new PropertyMetadata(false, OnOpenChanged));

        /// <summary>
        /// Opens or closes a window of type 'WindowType'.
        /// </summary>
        private static void OnOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var me = (OpenCloseWindowBehavior)d;
            if ((bool)e.NewValue)
            {
                object instance = Activator.CreateInstance(me.WindowType);
                if (instance is Window)
                {
                    Window window = (Window)instance;
                    window.Closing += (s, ev) => 
                    {
                        if (me.Open) // window closed directly by user
                        {
                            me._windowInstance = null; // prevents repeated Close call
                            me.Open = false; // set to false, so next time Open is set to true, OnOpenChanged is triggered again
                        }
                    }; 
                    window.Show();
                    me._windowInstance = window;
                }
                else
                {
                    // could check this already in PropertyChangedCallback of WindowType - but doesn't matter until someone actually tries to open it.
                    throw new ArgumentException(string.Format("Type '{0}' does not derive from System.Windows.Window.", me.WindowType));
                }
            }
            else 
            {
                if (me._windowInstance != null)
                    me._windowInstance.Close(); // closed by viewmodel
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 喜欢这个解决方案!我将其更改为 Behavior&lt;ContentControl&gt; 以便能够将它用于 Windows 和 UserControls (2认同)
  • 我遇到过几次从其他人那里链接的这个答案。因此,既然我不断回到这里,我会指出我唯一一直缺少的是它的原因......就像“我为什么要在服务/信使方法上使用它?” (2认同)
  • @DonBoitnott 这种方法提供了一些**显着的好处**。考虑使用服务/信使方法。突然,您希望为窗口定义一个“PlacementTarget”(例如,鼠标位置,或相对于 UIControl 的左/右/上/下等)。或者您希望定义偏移量,或者例如“Popup”的其他技巧。在服务/信使方法中,这些必须**公开**为服务的公共API中的参数,更不用说可以例如从不了解UI的视图模型内调用服务了。(**继续**) (2认同)
  • @DonBoitnott(**继续**)服务方法([此处](/sf/answers/1809233471/)周围的[ones](/sf/answers/1165712061/))无论如何)通常会在传递一个“对象”时停止,该对象应该是要分配的“Window.Content”。使用 **this** 答案的方法还使您能够简单地注册依赖属性,例如“PlacementTarget”(例如“UIElement”),并且突然之间,**您可以在 XAML 中设置它**(其中所有UI 信息可用)。因此,您可以立即从“ViewModel”和“UserControl”设置内容! (2认同)

Jer*_*all 5

我过去通过引入a的概念来处理这种情况WindowManager,这是一个可怕的名字,所以让我们把它与a配对WindowViewModel,这只是稍微不那么可怕 - 但基本的想法是:

public class WindowManager
{
    public WindowManager()
    {
        VisibleWindows = new ObservableCollection<WindowViewModel>();
        VisibleWindows.CollectionChanged += OnVisibleWindowsChanged;            
    }
    public ObservableCollection<WindowViewModel> VisibleWindows {get; private set;}
    private void OnVisibleWindowsChanged(object sender, NotifyCollectionChangedEventArgs args)
    {
        // process changes, close any removed windows, open any added windows, etc.
    }
}

public class WindowViewModel : INotifyPropertyChanged
{
    private bool _isOpen;
    private WindowManager _manager;
    public WindowViewModel(WindowManager manager)
    {
        _manager = manager;
    }
    public bool IsOpen 
    { 
        get { return _isOpen; } 
        set 
        {
            if(_isOpen && !value)
            {
                _manager.VisibleWindows.Remove(this);
            }
            if(value && !_isOpen)
            {
                _manager.VisibleWindows.Add(this);
            }
            _isOpen = value;
            OnPropertyChanged("IsOpen");
        }
    }    

    public event PropertyChangedEventHandler PropertyChanged = delegate {};
    private void OnPropertyChanged(string name)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我只是非常偶然地把它扔在一起; 你当然希望根据你的具体需求调整这个想法.

但是,任何人,基本前提是你的命令可以处理WindowViewModel对象,IsOpen适当地切换标志,经理类处理打开/关闭任何新窗口.有很多种可能的方法可以做到这一点,但过去它对我来说很有效(实际实施时并没有在我的手机上一起扔,也就是说)


San*_*der 5

对于纯粹主义者来说,一个合理的方法是创建一个服务来处理您的导航。简短摘要:创建一个 NavigationService,在 NavigationService 上注册您的视图并使用视图模型中的 NavigationService 进行导航。

例子:

class NavigationService
{
    private Window _a;

    public void RegisterViewA(Window a) { _a = a; }

    public void CloseWindowA() { a.Close(); }
}
Run Code Online (Sandbox Code Playgroud)

要获得对 NavigationService 的引用,您可以在其之上进行抽象(即 INavigationService)并通过 IoC 注册/获取它。更恰当地说,您甚至可以创建两个抽象,一个包含注册方法(由视图使用),另一个包含执行器(由视图模型使用)。

有关更详细的示例,您可以查看严重依赖 IoC 的 Gill Cleeren 的实现:

http://www.silverlightshow.net/video/Applied-MVVM-in-Win8-Webinar.aspx 00:36:30 开始


Oli*_*ell 4

实现此目的的一种方法是视图模型请求关闭子窗口:

public class ExampleUserControl_ViewModel
{
    public Action ChildWindowsCloseRequested;

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后,视图将订阅其视图模型的事件,并在触发时负责关闭窗口。

public class ExampleUserControl : UserControl
{
    public ExampleUserControl()
    {
        var viewModel = new ExampleUserControl_ViewModel();
        viewModel.ChildWindowsCloseRequested += OnChildWindowsCloseRequested;

        DataContext = viewModel;
    }

    private void OnChildWindowsCloseRequested()
    {
        // ... close child windows
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

因此,这里视图模型可以确保子窗口关闭,而无需了解视图。

  • 您还可以将 UserControl 的 DataContext 设置为您的 ViewModel,从而摆脱 ViewModel 公共属性。这将需要对事件注册进行一些转换,但这是一个很好的做法,因为在 MVVM 中,您无论如何都需要将 UserControl.DataContext 设置为 ViewModel。另外,请务必在调用之前执行一些验证以确保您的 ChildWindowsCloseRequested 不为 null,否则您将收到异常。 (4认同)