0

Только пытаюсь разобраться с Wpf MVMM.Есть такая разметка.

<Window x:Class="RealPolyclinic.MainWindow"
        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:local="clr-namespace:RealPolyclinic"
        xmlns:vm="clr-namespace:RealPolyclinic.ViewModels"
        xmlns:views="clr-namespace:RealPolyclinic.Views"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <DataTemplate x:Name="AdPViewTemplate" DataType="{x:Type vm:AddPatientVM}">
            <views:AddPatient />
        </DataTemplate>
        <DataTemplate x:Name="SrchViewTemplate" DataType="{x:Type vm:SearchPatientVM}">
            <views:SearchPatient/>
        </DataTemplate>
        <DataTemplate x:Name="OneMorePViewTemplate" DataType="{x:Type vm:OneMoreVM}">
            <views:OneMoreView />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <DockPanel Grid.Row="0" Grid.Column="0" Grid.RowSpan="5" Background="Black">
            <StackPanel>
                <Button Command="{Binding gotoAdp}">1st page</Button>
                <Button Command="{Binding gotoSrch}">2nd PAge</Button>
            </StackPanel>
        </DockPanel>
        <ContentControl Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="5" Grid.RowSpan="5" Content="{Binding CurrentView}"/>
    </Grid>
</Window>

Ей принадлежит такая ViewModel:MainVM.

public class MainVM : BaseViewModel
    {
        private BaseViewModel _currentView;
        public BaseViewModel CurrentView
        {
            get { return _currentView; }
            set
            {
                _currentView = value;
                OnPropertyChanged();
            }
        }

        public ICommand gotoAdp { get; set; }
        public ICommand gotoSrch { get; set; }

        public MainVM()
        {
            gotoAdp = new RelayCommand(x => CurrentView = new AddPatientVM());
            gotoSrch = new RelayCommand(x => CurrentView = new SearchPatientVM());
        }
    }

При переходе на любой из пользовательских UserControl.К примеру.

<UserControl x:Class="RealPolyclinic.Views.AddPatient"
             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:RealPolyclinic.Views"
             xmlns:vm="clr-namespace:RealPolyclinic.ViewModels"
             xmlns:views="clr-namespace:RealPolyclinic.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <DockPanel>
            <Button Command="{Binding NextView}">Privet</Button>
        </DockPanel>
    </Grid>
</UserControl>

И его ViewModel.

public class AddPatientVM : MainVM
    {
        public ICommand NextView { get; set; }
        public AddPatientVM()
        {
            NextView = new RelayCommand(x => CurrentView = new OneMoreVM());
        }
    }

Пытаюсь изменить свойство CurrentView как и в MainVm, но никакого эффекта,думаю это связано с DataContext. При нажатии кнопки в UserControl хотелось бы осуществить переход на любой другой UserControl.Соответственно нужно каким-то образом изменить свойство Content(ContentControl) в основном Window,каким образом это можно осуществить,используя MVVM.

1 ответ 1

0

Просто теория:

Объявите поле в вашей VM к примеру следующего типа:

public enum ViewType
{
    AddPatient,
    SearchPatient,
    OneMoreView
}

Далее делаете привязку к примеру на Tag вашего ContentControl, и меняете именно его.

А далее просто пишите триггер стилей для ContentControl где в зависимости от установленного тега, устанавливалась бы, необходимая View.


Оффтопик:

Вообще рекомендую изучить Prism Library, и взаимодействовать с регионами. Как пример, вы могли бы спокойно взять и определить в регионе активное View, а то что не нужно, сделать неактивным, таким образом ваш контент бы менялся в зависимости от потребностей.

2
  • Понял, а не могли бы подсказать как можно изменить DataContext переходя в UserControl,на его ViewModel.
    – Bantexx
    24 апр 2019 в 16:09
  • Не надо менять DataContext! Меняйте контент через триггер! Но не DataContext.
    – user206435
    24 апр 2019 в 18:47

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.