MVVM Light-用户控件为视图 [英] MVVM Light - User Controls as Views

查看:58
本文介绍了MVVM Light-用户控件为视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定使用MVVM Light库来帮助设计UI.经过大量的研究,反复试验后,我尚未找到所需的答案.我已经用Google搜索并阅读了我能找到的每个StackOverflow问题,但是,我的问题似乎在SO上是唯一的.

I have decided to use the MVVM Light library to help design a UI. After tons of research and trial and error, I have yet to find the answers I am looking for. I've googled and read each StackOverflow question I can find, however, my problem seems to be unique on SO.

我希望设计一个具有单个窗口的UI,并使用不同的Views/UserControls填充它.我既不需要用户控件之间的共享导航栏,也不想弹出多个窗口.每个View/UserControl应该绑定到自己的ViewModel,而MainWindow将绑定到MainViewModel.

I wish to design a UI with a single window and populate it with different Views/UserControls. I do NOT want a shared navigation bar among the UserControls nor do I want multiple windows to pop-up. Each View/UserControl should bind to its own ViewModel, while the MainWindow will bind to a MainViewModel.

示例场景-具有3个UserControl的MainWindow

Example scenario - MainWindow with 3 UserControls

1. MainWindow populates with first UserControl which has a listbox and 3 buttons, the first button is enabled.
2. User clicks the first button.
3. MainWindow populates with second UserControl.

或者,另外

 2. User selects choice from a listbox, button two and three become available.
 3. User clicks second/third button.
 4. MainWindow populates with second/third UserControl.

等等,

也许我的方法不切实际,但我认为这必须可行.我不明白如何使所有这些部分在概念上起作用.我的愿望绝不可能是独一无二的.如果您认为这是重复的问题,请重定向.干杯.

Perhaps my approach isn't realistic, but I feel this has to be possible. I do not understand how to make all of these pieces work conceptually. There is no way my desires are unique. If you feel this is duplicate question, please redirect. Cheers.

为了使事情更容易理解,我在下面添加了一些类.首先,我的App.xaml.

To make things easier to understand, I've included some classes below. First, my App.xaml.

<Application x:Class="Bobcat_BETA.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:views="clr-namespace:Bobcat_BETA.UserControls"
             xmlns:vm="clr-namespace:Bobcat_BETA.ViewModels"
             StartupUri="MainWindow.xaml"
             mc:Ignorable="d">
    <Application.Resources>
        <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />

        <DataTemplate DataType="{x:Type vm:SavedScenariosViewModel}">
            <views:SavedScenariosUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:ScenarioEditorViewModel}">
            <views:ScenarioEditorUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:SimulatorViewModel}">
            <views:SimulatorUserControl />
        </DataTemplate>

    </Application.Resources>
</Application>

MainWindow.xaml

MainWindow.xaml

<Window x:Class="Bobcat_BETA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Bobcat - Version:0.00"
    DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid>
    <ContentControl Content="{Binding CurrentView}"/>
</Grid>

ViewModelLocator.cs

ViewModelLocator.cs

namespace Bobcat_BETA.ViewModels
{

    public class ViewModelLocator
    {

        private static MainViewModel _main;

        public ViewModelLocator()
        {
            _main = new MainViewModel();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return _main;
            }
        }
    }
}

MainViewModel.cs

MainViewModel.cs

namespace Bobcat_BETA.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private ViewModelBase _currentViewModel;

        readonly static SavedScenariosViewModel _savedScenarioViewModel = new SavedScenariosViewModel();
        readonly static ScenarioEditorViewModel _scenarioEditorViewModel = new ScenarioEditorViewModel();
        readonly static SimulatorViewModel _simulatorViewModel = new SimulatorViewModel();

        public ViewModelBase CurrentViewModel
        {
            get
            {
                return _currentViewModel;
            }
            set
            {
                if (_currentViewModel == value)
                    return;
                _currentViewModel = value;
                RaisePropertyChanged("CurrentViewModel");
            }
        }

        public MainViewModel()
        {
            CurrentViewModel = MainViewModel._savedScenarioViewModel;
            SavedScenarioViewCommand = new RelayCommand(() => ExecuteSavedScenarioViewCommand());
            ScenarioEditorViewCommand = new RelayCommand(() => ExecuteScenarioEidtorViewCommand());
            SimulatorViewCommand = new RelayCommand(() => ExecuteSimulatorViewCommand());
        }

        public ICommand SavedScenarioViewCommand { get; private set; }
        public ICommand ScenarioEditorViewCommand { get; private set; }
        public ICommand SimulatorViewCommand { get; private set; }

        private void ExecuteSavedScenarioViewCommand()
        {
            CurrentViewModel = MainViewModel._savedScenarioViewModel;
        }

        private void ExecuteScenarioEidtorViewCommand()
        {
            CurrentViewModel = MainViewModel._scenarioEditorViewModel;
        }

        private void ExecuteSimulatorViewCommand()
        {
            CurrentViewModel = MainViewModel._simulatorViewModel;
        }
    }
}

SavedScenariosViewModel.cs

SavedScenariosViewModel.cs

namespace Bobcat_BETA.ViewModels
{
    public class SavedScenariosViewModel : ViewModelBase
    {

        public SavedScenariosViewModel()
        {
        }

        ObservableCollection<ScenarioModel> _scenarioModels = new ObservableCollection<ScenarioModel>()
        {
            new ScenarioModel() {Name = "Scenario 0", ID = 000, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 1", ID = 001, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 2", ID = 002, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 3", ID = 003, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 4", ID = 004, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 5", ID = 005, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 6", ID = 006, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 7", ID = 007, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 8", ID = 008, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 9", ID = 009, Desc = "This will describe the Scenario Model."}
        };
        public ObservableCollection<ScenarioModel> ScenarioModels
        {
            get { return _scenarioModels; }
        }

    }
}

SavedScenariosUserControl.xaml

SavedScenariosUserControl.xaml

<UserControl x:Class="Bobcat_BETA.UserControls.SavedScenariosUserControl"
             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:vm="clr-namespace:Bobcat_BETA.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Dictionaries/MasterDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <UserControl.Style>
        <DynamicResource ResourceKey="GeneralUserControl"/>
    </UserControl.Style>

    <Grid>
        <Label Content="Saved Scenario Selection" 
                Style="{StaticResource GeneralLabel}" HorizontalAlignment="Left" Margin="26,30,0,0" VerticalAlignment="Top" Height="62" Width="345"/>
        <Label Content="Chose Flight Model:" 
                Style="{StaticResource GeneralLabel2}"
                HorizontalAlignment="Left" Margin="27,111,0,0" VerticalAlignment="Top" Height="43" Width="345"/>
        <ListBox Style="{StaticResource GeneralListBox}"
                HorizontalAlignment="Left" Height="509" Margin="27,154,0,0" VerticalAlignment="Top" Width="345"
                ItemsSource="{Binding ScenarioModels}"/>

        <Button Content="New" 
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="948,601,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150" IsEnabled="True"
                Command="{Binding ScenarioEditorViewCommand}"/>

        <Button Content="Edit"
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="401,519,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150"
                Command="{Binding SaveScenariosViewCommand}"/>
        <Button Content="Load"
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="401,601,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150"
                Command="{Binding SimulatorViewCommand}"/>

    </Grid>
</UserControl>

如果不清楚,我也可以添加Model类,但是我假设您可以从发生的事情中进行推断.谢谢.

If anything is unclear, I can add the Model classes as well, but I assume you can make inferences from what is going on. Thanks.

推荐答案

所以您的方法很合理.为了获得该功能,您必须使用某些复杂的功能.我必须使用包含所有视图模型的"MainViewModel".这些视图模型的行为是,当数据上下文切换到其他视图模型时,相应的用户控件将更改为适当的视图. Sheridan在此处回答了一个很好的例子.使用适当的数据模板连接到您的app.xaml,数据上下文切换将像magic:D

So your approach is very plausible. There are certain intricacies you'll have to use in order to get that functionality. I had to use a "MainViewModel" which contained all the view models. These view models behave such that when the data context switched to a different view model, the corresponding user control would change to the appropriate view. A good example which I followed was answered by Sheridan here. Hook into your app.xaml with the appropriate data templates and data context switches will be handled like magic :D

在我与Sheridan的示例有所不同的地方(因为我不想创建一个单独的中继命令类/对象),我实际上使用了mvvm light(galasoft)将消息从我的视图模型发送到消息,返回给"MainViewModel",切换其数据上下文.可以在此处找到使用MVVM光消息传递的一个很好的例子.从子级"视图模型发送消息,并将其注册到"MainViewModel"中.

Where I diverged from Sheridan's example (because I didn't want to create a separate relay command class/object), I actually used mvvm light (galasoft) to send messages from my viewmodels to message back to the "MainViewModel" to switch its data context. A good example of using MVVM light messaging can be found here. Send the message from the "child" View Model and register it in the "MainViewModel."

祝你好运!

这篇关于MVVM Light-用户控件为视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆