最好的方式,使不同的意见/禁用根据需要控制在MainViewModel的状态(Best way to

2019-10-20 16:34发布

我有我开发一个应用程序。 它可以在两种状态(连接和断开)。 有一个在我的MainViewModel是跟踪当前状态的布尔属性。

我在我的应用中有许多其他的意见(和的ViewModels)。 当应用程序进入断开状态,我需要做几个控件(不是全部)在禁用的每个视图。 当应用程序是有在连接状态那么显然我需要启用那些相同的控制。

我想知道什么是做到这一点的好办法?

Answer 1:

我猜你有你的只有一个实例MainViewModel

因此,通过静态财产公开这个唯一的实例,甚至使之成为单身

这样,您就可以轻松共享视图之间的连接状态。

using System.ComponentModel;

namespace WpfMagic
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private static readonly MainViewModel instance = new MainViewModel();

        public static MainViewModel Instance { get { return instance; } }

        private bool isConnected;
        public bool IsConnected
        {
            get { return isConnected; }
            set
            {
                if (value != isConnected)
                {
                    isConnected = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("IsConnected"));
                }
            }
        }

        private MainViewModel()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
}

最棘手的部分是静态绑定,但除此之外,它很简单:

你的第一个观点:

<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Send Spams</Button>

另一个:

<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">DDOS SO</Button>

和最后一个:

<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Open Lol Cats Videos</Button>

为了测试它,你可以使用CheckBox以另一种观点:

<CheckBox IsChecked="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Is Connected?</CheckBox>


Answer 2:

你可以使用ViewModelLocator并在那里有一个单MainViewModel。 这将允许你从任何视图模型访问MainVM。 从那里直接访问所需的布尔属性。

希望这可以帮助。 ViewModelLocator IoC容器 , MVVM ViewModelLocator



Answer 3:

视图模型定位模式是一种选择,而不是一个坏的。

我会从的NuGet建议安装MVVM轻如在你的模板插头。

另一种替代方法是使用MVVM光的消息传递框架。 在这种情况下,你是主视图模型发出一条消息,当你的状态的改变,你的其他视图模型,假定绑定到你的意见,可以订阅。

这样做的好处是每个视图模型可以以任何方式回应的行为。 对于那些只需要布尔结合,创造哪些寄存器到消息并更新的特性的基本视图模式。 对于其他视图模型,你可能要改变可以执行命令绑定或更新标签等。



文章来源: Best way to enable/disable controls on different Views depending on a state in the MainViewModel
标签: c# wpf mvvm