ViewModel comunication MVVM

Eduardo Gomez 3,416 Reputation points
2022-07-21T20:12:39.607+00:00

I have this ViewModdel

[AddINotifyPropertyChangedInterface]  
public class MainWindowViewModel  
{  
    public GeoServices GeoServices  
    {  
        get; set;  
    }  
    public AirportServices Services  
    {  
        get; set;  
    }  
  
    public ObservableCollection<Airport> AirportsList  
    {  
        get; set;  
    }  
  
  
    private Airport? _SelectedItem;  
    public Airport? SelectedItem  
    {  
        get => _SelectedItem;  
        set  
        {  
            if (_SelectedItem != value)  
            {  
                _SelectedItem = value;  
                Details();  
            }  
        }  
    }  
  
    public string? CurrentCity  
    {  
        get; set;  
    }  
  
    public MainWindowViewModel()  
    {  
        //SelectedItem = new Airport  
        //{  
        //    OnAnyPropertiesChanged = () => { MyProperty?.RaiseCanExecuteChanged(); }  
        //};  
        Services = new AirportServices();  
  
        GeoServices = new GeoServices();  
  
        AirportsList = new ObservableCollection<Airport>();  
  
        GetAirportList();  
  
        GetOrigin();  
    }  
    private async void GetAirportList()  
    {  
        var temppList = await Services.GetAirportsAsync();  
  
        var teplObservable = new ObservableCollection<Airport>();  
        foreach (var item in temppList!)  
        {  
            teplObservable.Add(item);  
        }  
  
        AirportsList = teplObservable;  
  
    }  
  
    private async void GetOrigin()  
    {  
        var accessStatus = await Geolocator.RequestAccessAsync();  
  
        if (accessStatus == GeolocationAccessStatus.Allowed)  
        {  
            var locator = new Geolocator();  
  
            var pos = await locator.GetGeopositionAsync();  
  
            var userCity = await GeoServices.GetLocation(pos.Coordinate.Latitude,pos.Coordinate.Longitude);  
  
            CurrentCity = userCity?.address?.city;  
        }  
    }  
  
    private void Details()  
    {  
        if (string.IsNullOrEmpty(SelectedItem?.city)) { return; }  
  
        var CityDetailsWindow = new CittyDetailsWinow();  
  
        CityDetailsViewModel viewModel = new CityDetailsViewModel { SelecteItem = SelectedItem};  
  
        CityDetailsWindow.Show();  
  
    }  

I want to get the SelectedItem into the SelectedItem in the Second View Model

This is my second view model

[AddINotifyPropertyChangedInterface]  
public class CityDetailsViewModel  
{  
  
    public Airport? SelecteItem // null  
    {  
        get; set;  
    }  
    public CityDetailsViewModel()  
    {  
  
  
    }  
}  

UI

<syncfusion:ChromelessWindow  
    x:Class="Travel.Views.CittyDetailsWinow"  
    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:vm="clr-namespace:Travel.ViewModels"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    xmlns:syncfusion="http://schemas.syncfusion.com/wpf"  
    xmlns:syncfusionskin="clr-namespace:Syncfusion.SfSkinManager;assembly=Syncfusion.SfSkinManager.WPF"  
    Width="400"  
    Height="800"  
    syncfusionskin:SfSkinManager.Theme="{syncfusionskin:SkinManagerExtension ThemeName=FluentDark}"  
    AllowsTransparency="True"  
    CornerRadius="10"  
    ShowIcon="False"  
    mc:Ignorable="d">  
  
    <Window.DataContext>  
        <vm:CityDetailsViewModel/>  
    </Window.DataContext>  
  
    <Grid>  
        <TextBlock Text="{Binding SelecteItem.city}"/>  
    </Grid>  
      
</syncfusion:ChromelessWindow>  
  

  
  
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,678 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
767 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 40,661 Reputation points Microsoft Vendor
    2022-07-22T09:58:24.16+00:00

    If you want to access the value of SelectedItem in MainWindowViewModel from CityDetailsViewModel class, you could try to refer to the code below.
    MainWindow.xaml:

     <Window.DataContext>  
            <local:MainWindowViewModel/>  
        </Window.DataContext>  
          
        <Grid>  
            <ComboBox Height="50" ItemsSource="{Binding AirportsList}" SelectedItem="{Binding SelectedItem}" DisplayMemberPath="city"/>  
        </Grid>  
    

    MainWindow.xaml.cs:

    using System.Collections.ObjectModel;  
    using System.Windows;  
    namespace ViewModelAccess  
    {  
        public partial class MainWindow : Window  
        {  
            public MainWindow()  
            {  
                InitializeComponent();  
            }  
        }  
        public class MainWindowViewModel  
        {  
            public MainWindowViewModel()  
            {  
                AirportsList = new ObservableCollection<Airport>()   
                {   
                    new Airport(){ city="London"},  
                    new Airport(){ city="Beijing"},  
                    new Airport(){ city="NewYork"},  
                    new Airport(){ city="Singapore"},  
                };  
            }  
         
            public ObservableCollection<Airport> AirportsList  
            {  
                get; set;  
            }  
            private Airport? _SelectedItem;  
            public Airport? SelectedItem  
            {  
                get => _SelectedItem;  
                set  
                {  
                    if (_SelectedItem != value)  
                    {  
                        _SelectedItem = value;  
                        Details();  
                    }  
                }  
            }  
            private void Details()  
            {  
                if (string.IsNullOrEmpty(SelectedItem?.city)) { return; }  
      
                var CityDetailsWindow = new CittyDetailsWinow();  
      
                CityDetailsViewModel viewModel = new CityDetailsViewModel(this) ;  
                CityDetailsWindow.DataContext = viewModel;  
                CityDetailsWindow.Show();  
      
            }  
        }  
        public class Airport  
        {  
            public string city { get; set; }  
        }  
    }  
    

    CittyDetailsWinow:

     <StackPanel>  
           
            <TextBlock Background="LightGreen" Text="{Binding CitySelecteItem.city}"/>  
        </StackPanel>  
    

    Codebehind:
    223698-33.txt

    The result:

    223697-image.png

    Update:
    I tested your project, you can use below code.

      private void Details()  
        {  
            if (string.IsNullOrEmpty(SelectedItem?.city)) { return; }  
      
            var CityDetailsWindow = new CittyDetailsWinow();  
              
            CityDetailsWindow.DataContext= new CityDetailsViewModel(SelectedItem);  
            CityDetailsWindow.Show();  
      
        }  
    

    CittyDetailsWinow:

    <syncfusion:ChromelessWindow  
        x:Class="Travel.Views.CittyDetailsWinow"  
       ...  
       >  
        <Grid>  
            <TextBlock Text="{Binding SelectedItem.city}" Background="Gray" Width="200" Height="50"  FontSize="20" VerticalAlignment="Center" HorizontalAlignment="Center"/>  
        </Grid>  
          
    </syncfusion:ChromelessWindow>  
    

    224735-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Eduardo Gomez 3,416 Reputation points
    2022-07-25T20:40:56.247+00:00

    The thing is that I am not using code behind, I am using MVVM. I have 0 code in the xaml.cs file

    I have only view models

    224499-image.png

    When I debug, I see everything

    <Window.DataContext>  
            <vm:CityDetailsViewModel/>  
        </Window.DataContext>  
      
        <Grid>  
            <TextBlock Text="{Binding SelectedItem.city}"  FontSize="20" VerticalAlignment="Center" HorizontalAlignment="Center"/>  
        </Grid>  
    

    But when I start the application I do not see the textbox