How to pass data from MainWindow to multiple viewmodels

Hi, I have the following codes where I want to pass dropdown selected data from one window to another window's viewmodel. For example, I want to pass values selected from the dropdowns in MainWindow to ChartViewModel. How do I achieve this? Also, how do I change title of ChartWindow using the values selected from the dropdowns in MainWindow?

MainWindow.xaml:

<Window x:Class="SyncfusionWpfDropdownTest.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:SyncfusionWpfDropdownTest"
        xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
        mc:Ignorable="d"
        Title="Trading App" Height="450" Width="800">
    <Window.DataContext>
        <local:ViewModel x:Name="viewModel"/>
    </Window.DataContext>
    <Grid>
        <syncfusion:TabControlExt Name="tabControlExt">
            <syncfusion:TabItemExt Header="Data">
                <Grid Margin="10">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Label Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" FontWeight="Bold">Market:</Label>
                    <StackPanel Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" Margin="0,0,0,0">
                        <syncfusion:DropDownButtonAdv IconHeight="1" IconWidth="1" SizeMode="Normal" x:Name="MarketDropDown" Label="Market">
                            <syncfusion:DropDownMenuGroup ScrollBarVisibility="Visible" ItemsSource="{Binding Markets}">
                                <syncfusion:DropDownMenuGroup.ItemTemplate>
                                    <DataTemplate>
                                        <syncfusion:DropDownMenuItem Header="{Binding Name}" HorizontalAlignment="Left" Click="DropDownMenuItem_MarketClick">
                                        </syncfusion:DropDownMenuItem>
                                    </DataTemplate>
                                </syncfusion:DropDownMenuGroup.ItemTemplate>
                            </syncfusion:DropDownMenuGroup>
                        </syncfusion:DropDownButtonAdv>
                    </StackPanel>
                    <Label Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left" Margin="0,0,0,0" FontWeight="Bold">Delivery Month:</Label>
                    <StackPanel Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" Margin="0,0,0,0">
                        <syncfusion:DropDownButtonAdv IconHeight="1" IconWidth="1" SizeMode="Normal" x:Name="DeliveryMonthDropDown" Label="Delivery Month">
                            <syncfusion:DropDownMenuGroup ScrollBarVisibility="Visible" ItemsSource="{Binding DeliveryMonths}">
                                <syncfusion:DropDownMenuGroup.ItemTemplate>
                                    <DataTemplate>
                                        <syncfusion:DropDownMenuItem Header="{Binding Month}" HorizontalAlignment="Left" Click="DropDownMenuItem_DeliveryMonthClick">
                                        </syncfusion:DropDownMenuItem>
                                    </DataTemplate>
                                </syncfusion:DropDownMenuGroup.ItemTemplate>
                            </syncfusion:DropDownMenuGroup>
                        </syncfusion:DropDownButtonAdv>
                    </StackPanel>
                    <Label Grid.Row="2" Grid.Column="0" HorizontalAlignment="Left" Margin="0,0,0,0" FontWeight="Bold">Country:</Label>
                    <StackPanel Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" Margin="0,0,0,0">
                        <syncfusion:DropDownButtonAdv IconHeight="1" IconWidth="1" SizeMode="Normal" x:Name="CountryDropDown" Label="Country">
                            <syncfusion:DropDownMenuGroup ScrollBarVisibility="Visible" ItemsSource="{Binding Countries}">
                                <syncfusion:DropDownMenuGroup.ItemTemplate>
                                    <DataTemplate>
                                        <syncfusion:DropDownMenuItem Header="{Binding Name}" HorizontalAlignment="Left" Click="DropDownMenuItem_CountryClick">
                                        </syncfusion:DropDownMenuItem>
                                    </DataTemplate>
                                </syncfusion:DropDownMenuGroup.ItemTemplate>
                            </syncfusion:DropDownMenuGroup>
                        </syncfusion:DropDownButtonAdv>
                    </StackPanel>
                    <Label Grid.Row="3" Grid.Column="0" HorizontalAlignment="Left" Margin="0,0,0,0" FontWeight="Bold">Date:</Label>
                    <syncfusion:CalendarEdit Grid.Row="3" Grid.Column="1" Name="DateCalendarEditStart" HorizontalAlignment="Left" Margin="0,0,0,0" Height="200" Width="200" AllowMultiplySelection="True"/>
                    <syncfusion:CalendarEdit Grid.Row="3" Grid.Column="1" Name="DateCalendarEditEnd" HorizontalAlignment="Left" Margin="200,0,0,0" Height="200" Width="200" AllowMultiplySelection="True"/>
                    <syncfusion:ButtonAdv x:Name="ChartButton" Grid.Row="1" Grid.Column="1" Height="25" Width="200" IconHeight="1" IconWidth="1" SizeMode="Normal" VerticalAlignment="Top" HorizontalAlignment="Right" Label="Open Market Chart" Click="ButtonAdvItem_ChartButtonClick"/>
                    <syncfusion:ButtonAdv x:Name="TableButton" Grid.Row="4" Grid.Column="1" Height="25" Width="200" IconHeight="1" IconWidth="1" SizeMode="Normal" VerticalAlignment="Top" HorizontalAlignment="Right" Label="Open Economic Calendar Table" Click="ButtonAdvItem_TableButtonClick"/>
                </Grid>
            </syncfusion:TabItemExt>
        </syncfusion:TabControlExt>
    </Grid>
</Window>

MainWindow.xaml.cs:

using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;
using System.Windows;


namespace SyncfusionWpfDropdownTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string selectedCountry = "";
        string selectedMarket = "";
        string selectedDeliveryMonth = "";
        Date selectedStartDate = new Date();
        Date selectedEndDate = new Date();


        public MainWindow()
        {
            InitializeComponent();
        }
        private void DropDownMenuItem_CountryClick(object sender, RoutedEventArgs e)
        {
            selectedCountry = (sender as DropDownMenuItem)?.Header?.ToString()?? string.Empty;
            CountryDropDown.Label = selectedCountry;
            viewModel.CountrySavedValue = selectedCountry;
        }
        private void DropDownMenuItem_MarketClick(object sender, RoutedEventArgs e)
        {
            selectedMarket = (sender as DropDownMenuItem)?.Header?.ToString()?? string.Empty;
            MarketDropDown.Label = selectedMarket;
            viewModel.MarketSavedValue = selectedMarket;
        }
        private void DropDownMenuItem_DeliveryMonthClick(object sender, RoutedEventArgs e)
        {
            selectedDeliveryMonth = (sender as DropDownMenuItem)?.Header?.ToString()?? string.Empty;
            DeliveryMonthDropDown.Label = selectedDeliveryMonth;
            viewModel.DeliveryMonthSavedValue = selectedDeliveryMonth;
        }
        private void ButtonAdvItem_ChartButtonClick(object sender, RoutedEventArgs e)
        {
            ChartWindow chartWindow = new ChartWindow();
            chartWindow.Show();
        }
        private void ButtonAdvItem_TableButtonClick(object sender, RoutedEventArgs e)
        {
            List<Date> startDates = DateCalendarEditStart.SelectedDatesList;
            List<Date> endDates = DateCalendarEditEnd.SelectedDatesList;


            if (startDates != null && startDates.Count > 0)
            {
                Date startDate = startDates.Min();
            }
            if (endDates != null && endDates.Count > 0)
            {
                Date endDate = endDates.Max();
            }
        }
    }
}

ViewModel.cs:

using System.Collections.ObjectModel;
using System.Web;
using Npgsql;


namespace SyncfusionWpfDropdownTest
{
    public class ViewModel
    {
        private string _countrySavedValue = string.Empty;
        private string _marketSavedValue = string.Empty;
        private string _deliverymonthSavedValue = string.Empty;
        public ObservableCollection<Country> Countries { get; set; }
        public ObservableCollection<Market> Markets { get; set; }
        public ObservableCollection<DeliveryMonth> DeliveryMonths { get; set; }
        public string CountrySavedValue
        {
            get { return _countrySavedValue; }
            set { _countrySavedValue = value; }
        }
        public string MarketSavedValue
        {
            get { return _marketSavedValue; }
            set { _marketSavedValue = value; MakeDeliveryMonthQuery(); }
        }
        public string DeliveryMonthSavedValue
        {
            get { return _deliverymonthSavedValue; }
            set { _deliverymonthSavedValue = value; }
        }
        private void MakeDeliveryMonthQuery()
        {
            DeliveryMonths.Clear();
            NpgsqlConnection conn2 = new NpgsqlConnection("Host=192.168.1.2; Port=5432; Database=tradingapp; Username=vorlket; Password=Vcsokr.");
            conn2.Open();
            string query2 = "SELECT DISTINCT \"Delivery Month\" FROM Futures WHERE Name = '" + MarketSavedValue + "' ORDER BY \"Delivery Month\"";
            NpgsqlCommand cmd2 = new NpgsqlCommand(query2, conn2);
            NpgsqlDataReader reader2 = cmd2.ExecuteReader();
            while (reader2.Read())
            {
                DeliveryMonths.Add(new DeliveryMonth
                {
                    Month = reader2.GetString(0)
                });
            }
        }
        public ViewModel()
        {
            Countries = new ObservableCollection<Country>();
            Markets = new ObservableCollection<Market>();
            DeliveryMonths = new ObservableCollection<DeliveryMonth>();
            LoadData();
        }


        private void LoadData()
        {
            NpgsqlConnection conn = new NpgsqlConnection("Host=192.168.1.2; Port=5432; Database=tradingapp; Username=vorlket; Password=Vcsokr.");
            conn.Open();
            string query = "SELECT DISTINCT Country FROM EconomicCalendar ORDER BY Country";
            NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
            NpgsqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Countries.Add(new Country
                {
                    Name = reader.GetString(0)
                });
            }


            NpgsqlConnection conn1 = new NpgsqlConnection("Host=192.168.1.2; Port=5432; Database=tradingapp; Username=vorlket; Password=Vcsokr.");
            conn1.Open();
            string query1 = "SELECT DISTINCT Name FROM Futures ORDER BY Name";
            NpgsqlCommand cmd1 = new NpgsqlCommand(query1, conn1);
            NpgsqlDataReader reader1 = cmd1.ExecuteReader();
            while (reader1.Read())
            {
                Markets.Add(new Market
                {
                    Name = reader1.GetString(0)
                });
            }
        }
    }
}

ChartWindow.xaml:

<Window x:Class="SyncfusionWpfDropdownTest.ChartWindow"
        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:SyncfusionWpfDropdownTest"
        xmlns:chart="http://schemas.syncfusion.com/wpf" xmlns:syncfusion="clr-namespace:Syncfusion.UI.Xaml.Charts;assembly=Syncfusion.SfChart.WPF"
        mc:Ignorable="d"
        Title="ChartWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:ChartViewModel/>
    </Window.DataContext>


    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>


        <chart:SfChart Grid.Row="0">
            <syncfusion:SfChart.Behaviors>
                <syncfusion:ChartZoomPanBehavior EnableMouseWheelZooming="True" EnableSelectionZooming="True" EnablePanning="True" ResetOnDoubleTap="True">
                </syncfusion:ChartZoomPanBehavior>
            </syncfusion:SfChart.Behaviors>


            <chart:SfChart.PrimaryAxis>
                <chart:DateTimeAxis x:Name="XAxis1" LabelFormat="yyyy MM dd"/>
            </chart:SfChart.PrimaryAxis>


            <chart:SfChart.SecondaryAxis>
                <chart:NumericalAxis Header="Price"/>
            </chart:SfChart.SecondaryAxis>


            <chart:CandleSeries ShowTooltip="True" ItemsSource="{Binding Futures}" XBindingPath="Date" High="High" Low="Low" Open="Open" Close="Close"/>


            <chart:SfChart.TechnicalIndicators>
                <chart:BollingerBandIndicator ItemsSource="{Binding Futures}" Period="3" UpperLineColor="Blue" LowerLineColor="Red" XBindingPath="Date" Volume="Volume" SignalLineColor="Black" High="High" Low="Low" Open="Open" Close="Close"/>
            </chart:SfChart.TechnicalIndicators>
        </chart:SfChart>


        <chart:SfChart Grid.Row="1">
            <chart:SfChart.PrimaryAxis>
                <chart:DateTimeAxis LabelFormat="yyyy MM dd" ZoomFactor="{Binding Path=ZoomFactor,Source={x:Reference XAxis1},Mode=TwoWay}" ZoomPosition="{Binding Path=ZoomPosition,Source={x:Reference XAxis1},Mode=TwoWay}"/>
            </chart:SfChart.PrimaryAxis>


            <chart:SfChart.SecondaryAxis>
                <chart:NumericalAxis Header="Volume"/>
            </chart:SfChart.SecondaryAxis>
            <chart:ColumnSeries ShowTooltip="True" ItemsSource="{Binding Futures}" XBindingPath="Date" YBindingPath="Volume" Interior="Gray"/>
        </chart:SfChart>


        <chart:SfChart Grid.Row="2">
            <chart:SfChart.PrimaryAxis>
                <chart:DateTimeAxis LabelFormat="yyyy MM dd" ZoomFactor="{Binding Path=ZoomFactor,Source={x:Reference XAxis1},Mode=TwoWay}" ZoomPosition="{Binding Path=ZoomPosition,Source={x:Reference XAxis1},Mode=TwoWay}"/>
            </chart:SfChart.PrimaryAxis>


            <chart:SfChart.SecondaryAxis>
                <chart:NumericalAxis Header="Open Interest"/>
            </chart:SfChart.SecondaryAxis>
            <chart:ColumnSeries ShowTooltip="True" ItemsSource="{Binding Futures}" XBindingPath="Date" YBindingPath="OpenInterest" Interior="Gray"/>
        </chart:SfChart>
    </Grid>


</Window>

ChartViewModel.cs:

using Npgsql;

using System.Collections.ObjectModel;


namespace SyncfusionWpfDropdownTest
{
    public class ChartViewModel
    {
        private string _marketSavedValue = string.Empty;
        private string _deliverymonthSavedValue = string.Empty;
        public ObservableCollection<Market> Markets { get; set; }
        public ObservableCollection<DeliveryMonth> DeliveryMonths { get; set; }
        public string MarketSavedValue
        {
            get { return _marketSavedValue; }
            set { _marketSavedValue = value; }
        }
        public string DeliveryMonthSavedValue
        {
            get { return _deliverymonthSavedValue; }
            set { _deliverymonthSavedValue = value; }
        }
        public ObservableCollection<Futures> Futures { get; set; }
        public ChartViewModel()
        {
            Markets = new ObservableCollection<Market>();
            DeliveryMonths = new ObservableCollection<DeliveryMonth>();
            Futures = new ObservableCollection<Futures>();
            LoadData();
        }
        private void LoadData()
        {
            NpgsqlConnection conn = new NpgsqlConnection("Host=192.168.1.2; Port=5432; Database=tradingapp; Username=vorlket; Password=Vcsokr.");
            conn.Open();
            string query = "SELECT Date, High, Open, Close, Low, Volume, \"Open Interest\" FROM Futures WHERE Name = '" + MarketSavedValue + "' and \"Delivery Month\"='" + DeliveryMonthSavedValue + "'";
            NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
            NpgsqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Futures.Add(new Futures
                {
                    Date = reader.GetDateTime(0),
                    High = reader.GetDouble(1),
                    Open = reader.GetDouble(2),
                    Close = reader.GetDouble(3),
                    Low = reader.GetDouble(4),
                    Volume = reader.GetInt32(5),
                    OpenInterest = reader.GetInt32(6)
                });
            }
        }
    }
}



1 Reply 1 reply marked as answer

PV Priyanka Vijayasankar Syncfusion Team August 5, 2024 09:47 AM UTC

Hi Kook Jin Noh,

 

We have reviewed your query and created a sample to meet your requirements. Please find the attached sample below and let us know if you need any further assistance.

 

Regards,

Priyanka Vijayasankar


Attachment: DropDownButton_9ccb98.zip

Marked as answer
Loader.
Up arrow icon