StaticResource inside MainWindow passing through a Datacontext inside an UserControl and this Datacontext passing through another UserControl

Michell 45 Reputation points
2023-08-07T17:40:32.9766667+00:00

Could you clarify a question about StaticResource and hierarchy?

I have MainWindow.xaml (Window) and inside it I call NewChart.xaml (UserControl) through the command <vm:NewChart DataContext="{StaticResource _instance}" /> .

I would like to know how inside NewChart.xaml I can call another UserControl called NewMenuRight.xaml passing the StaticResource _instance that he inherited from MainWindow.xaml.

E.g.

MainWindow.xaml.cs:

public partial class MainWindow : Window
    {
        public MainWindowViewModel _instance { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            
            _instance = new MainWindowViewModel();
            DataContext = _instance;
        }

    }

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
      ...
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:views="clr-namespace:WpfApp1.Views" 
        xmlns:vm="clr-namespace:WpfApp1.ViewModels"       
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <vm:MainWindowViewModel x:Key="_instance" />
    </Window.Resources>
    <StackPanel>
        <views:NewChart DataContext="{StaticResource _instance}" />
    </StackPanel>
</Window>

MewChart.xaml

<UserControl x:Class="WpfApp1.NewChart"
      ...
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:views="clr-namespace:WpfApp1.Views"
        xmlns:vm="clr-namespace:WpfApp1.ViewModels"                
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <UserControl.Resources>
        <vm:MainWindowViewModel x:Key="_instance" />
    </UserControl.Resources>
    <StackPanel>
        <views:NewMenuRight DataContext="{StaticResource _instance}" />
    </StackPanel>
</UserControl>


NewChart.xaml.cs

public partial class NewChart: UserControl
    {
        public MainWindowViewModel _instance { get; set; }

        public NewChart()
        {
            InitializeComponent();

            
            _instance = new MainWindowViewModel();
            DataContext = _instance;
        }

    }

MainWindowViewModel.cs:

namespace WpfApp1.ViewModels;
public partial class MainWindowViewModel 
{
    private static MainWindowViewModel _instance; 
    public event PropertyChangedEventHandler PropertyChanged;
    private bool _novoMenuIsOpen { get; set; } 
    public bool NovoMenuIsOpen
    {
        get { return _novoMenuIsOpen; } 
        set
        {
            _novoMenuIsOpen = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NovoMenuIsOpen)));
        }
    }
    public void OpenMenu() 
    {
        NovoMenuIsOpen = true;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NovoMenuIsOpen)));
    }
   
    public void ClickCancelar(object sender, RoutedEventArgs args)
    {
        NovoMenuIsOpen = false;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NovoMenuIsOpen)));
    }
   
    public MainWindowViewModel()
    {
        NovoMenuIsOpen = false;
        _instance = this;
    }
}

NewMenuRight.xaml.cs

public partial class NewMenuRight: UserControl      
{          
	public MainWindowViewModel _instance { get; set; }          
	public NewChart()          
	{              
		InitializeComponent();                            
		_instance = new MainWindowViewModel();              
		DataContext = _instance;          
	}      
}

NewMenuRight.xaml

<UserControl ...
             xmlns:views="using:QuantPro.Views"
             xmlns:vm="using:QuantPro.ViewModels"
             mc:Ignorable="d" d:DesignWidth="300" d:DesignHeight="330"
             x:Class="WpfApp1.Views.NewMenuRight">
  <UserControl.Resources>
    <vm:MainWindowViewModel x:Key="_instance" />
  </UserControl.Resources>
  <Grid RowDefinitions="Auto Auto" >    
        <Button Grid.Column="0" Margin="0,10,0,0" Width="70" CornerRadius="10" Click="ClickCancelar" DataContext="{StaticResource _instance}">Cancel</Button>
      </Grid>
    </Grid>
  </Border>
  </Grid>
</UserControl>

The problem is: the NewMenuRight.xaml is creating a new instance of MainWindowViewModel and it is not changing the properties of the MainWindowViewModel that was instantiated in the initialization of MainWindow.xaml

I would like to click on Cancel Button(NewMenuRight.xaml) and it run the method ClickCancelar inside MainWindowViewModel.cs from current instance, not create a new one. Is it possible?

In resume: StaticResource inside MainWindow passing through a Datacontext (MainWindowViewModel) inside an UserControl(NewChart) and this Datacontext passing through another UserControl(NewMenuRight).

Thank you so much!

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,575 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,584 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.
786 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 47,176 Reputation points Microsoft Vendor
    2023-08-08T09:58:51.7+00:00

    Hi,@Michell . Welcome Microsoft Q&A. For the problem of click on Cancel Button(NewMenuRight.xaml) and it run the method ClickCancelar inside MainWindowViewModel.cs from current instance, I modified the code according to your situation. You could try looking at the code below.

    You can check the code below to see if it is what you want. If you still have problems, please let me know.

    NewMenuRight.xaml:

    <UserControl x:Class="WpfApp2.Views.NewMenuRight"
                ...
                 xmlns:local="clr-namespace:WpfApp2.Views"
                 mc:Ignorable="d" 
                 d:DesignHeight="450" d:DesignWidth="800">
     
        <Grid  >
            <CheckBox IsChecked="{Binding NovoMenuIsOpen}"/>
            <Button Grid.Column="0" Margin="0,10,0,0" Width="70"  Command="{Binding  ClickCancelarCommand}" >Cancel</Button>
        </Grid>
    </UserControl>
    
    
    

    NewMenuRight.xaml.cs:

     public partial class NewMenuRight : UserControl
        {
            public NewMenuRight()
            {
                InitializeComponent();
            }
        }
    
    

    NewChart.xaml:

    
    <UserControl x:Class="WpfApp2.Views.NewChart"
                 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:views="clr-namespace:WpfApp2.Views"
                 xmlns:vm="clr-namespace:WpfApp2.ViewModels"
                 mc:Ignorable="d" 
                 d:DesignHeight="450" d:DesignWidth="800">
        <UserControl.Resources>
            <vm:MainWindowViewModel x:Key="_instance" />
        </UserControl.Resources>
        <StackPanel>
            <views:NewMenuRight DataContext="{StaticResource _instance}" />
        </StackPanel>
    </UserControl>
    
    

    NewChart.xaml.cs:

    
     public partial class NewChart : UserControl
        {
            public MainWindowViewModel _instance { get; set; }
    
            public NewChart()
            {
                InitializeComponent();
    
    
                _instance = new MainWindowViewModel();
                DataContext = _instance;
            }
        }
    
    

    RelayCommand:

    
     public class RelayCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Predicate<object> _canExecute;
    
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                _execute(parameter);
            }
        }
    
    

    MainWindowViewModel.cs :

    
    namespace WpfApp2.ViewModels
    {
        public class MainWindowViewModel : INotifyPropertyChanged
        {
            private static MainWindowViewModel _instance;
         
            private bool _novoMenuIsOpen { get; set; }
            public bool NovoMenuIsOpen
            {
                get { return _novoMenuIsOpen; }
                set
                {
                    _novoMenuIsOpen = value;
                    OnPropertyChanged("NovoMenuIsOpen");
                }
            }
            public RelayCommand ClickCancelarCommand { get; }
    
    
            public MainWindowViewModel()
            {
                NovoMenuIsOpen = false;
                _instance = this;
                ClickCancelarCommand = new RelayCommand(ClickCancelar);
            }
    
            public void OpenMenu()
            {
                NovoMenuIsOpen = true;
               
            }
    
            public void ClickCancelar(object obj)
            {
                NovoMenuIsOpen = false;
              
            }
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    
    
    

    MainWindow.xaml:

    
    <Window x:Class="WpfApp2.MainWindow"
          ...
            xmlns:local="clr-namespace:WpfApp2"
               xmlns:views="clr-namespace:WpfApp2.Views"
                 xmlns:vm="clr-namespace:WpfApp2.ViewModels"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <vm:MainWindowViewModel x:Key="_instance"/>
        </Window.Resources>
        <StackPanel>
            <views:NewChart DataContext="{StaticResource _instance}" />
        </StackPanel>
    </Window>
    
    

    MainWindow.xaml.cs:

    
      public partial class MainWindow : Window
        {
            public MainWindowViewModel _instance { get; set; }
    
            public MainWindow()
            {
                InitializeComponent();
    
    
                _instance = new MainWindowViewModel();
                DataContext = _instance;
            }
        }
    
    

    The result:

    7


    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.


6 additional answers

Sort by: Most helpful
  1. Itechflow 0 Reputation points
    2023-08-08T11:36:28.2733333+00:00

    Itechflow stands tall as the trusted Manufacturers of electromagnetic flow meters in Ghaziabad, where companies grow and precision matters. Itechflow has acquired a reputation as the go-to source for all your flow meter needs because to its commitment to delivering excellent quality and dependable solutions.

    Itechflow provides a diverse range of electromagnetic flow meters for a variety of applications and industries. Itechflow has a solution for measuring the flow of liquids in water treatment plants, wastewater management systems, chemical processing facilities, and irrigation systems. Their extensive product line comprises both small and remote-mounted flow meters, making installation and integration into existing systems simple.

    Itechflow has established itself as one of the most reliable electromagnetic flow meter manufacturers in Ghaziabad. Itechflow has been the preferred choice for sectors seeking trustworthy and precise flow measurement solutions because to its unwavering focus on quality, diversified product choices, personalized solutions, great customer service, and commitment to sustainability.

    If you're seeking an electromagnetic flow meter that combines precision, longevity, and great customer service, Itechflow is the name to know. They have won the faith and confidence of clients from a variety of industries due to their knowledge and commitment to excellence. Contact Itechflow today to discover the benefits of working with a reliable partner for all of your flow meter requirements in Ghaziabad and beyond.

    We provide products and services in these popular cities in India:-

    Electromagnetic Flow Meter Manufacturers in Alwar

    Electromagnetic Flow Meter Manufacturers in Udaipur

    Electromagnetic Flow Meter Manufacturers in Kota

    Electromagnetic Flow Meter Manufacturers in Bikaner

    Electromagnetic Flow Meter Manufacturers in Jaisalmer

    Electromagnetic Flow Meter Manufacturers in Jodhpur

    Electromagnetic Flow Meter Manufacturers in Neemrana

    Electromagnetic Flow Meter Manufacturers in Delhi

    Electromagnetic Flow Meter Manufacturers in Noida

    Electromagnetic Flow Meter Manufacturers in Gurgaon

    Electromagnetic Flow Meter Manufacturers in Faridabad

    Electromagnetic Flow Meter Manufacturers in Ghaziabad

    Electromagnetic Flow Meter Manufacturers in Mumbai

    Electromagnetic Flow Meter Manufacturers in Thane

    Electromagnetic Flow Meter Manufacturers in Solapur

    Electromagnetic Flow Meter Manufacturers in Pune

    Electromagnetic Flow Meter Manufacturers in Bhopal

    Electromagnetic Flow Meter Manufacturers in Indore

    Electromagnetic Flow Meter Manufacturers in Nashik

    Electromagnetic Flow Meter Manufacturers in Kolkata

    Electromagnetic Flow Meter Manufacturers in Howrah

    Electromagnetic Flow Meter Manufacturers in Surat

    Electromagnetic Flow Meter Manufacturers in Ahmedabad

    Electromagnetic Flow Meter Manufacturers in Rajkot

    Electromagnetic Flow Meter Manufacturers in Vadodara

    Electromagnetic Flow Meter Manufacturers in Nagpur

    Electromagnetic Flow Meter Manufacturers in Jabalpur

    Electromagnetic Flow Meter Manufacturers in Gwalior

    Electromagnetic Flow Meter Manufacturers in Ujjain

    Electromagnetic Flow Meter Manufacturers in Guwahati

    Electromagnetic Flow Meter Manufacturers in Agra

    Electromagnetic Flow Meter Manufacturers in Lucknow

    Electromagnetic Flow Meter Manufacturers in Kanpur

    Electromagnetic Flow Meter Manufacturers in Meerut

    Electromagnetic Flow Meter Manufacturers in Varanasi

    Electromagnetic Flow Meter Manufacturers in Chandigarh

    Electromagnetic Flow Meter Manufacturers in Ludhiana

    Electromagnetic Flow Meter Manufacturers in Amritsar

    Electromagnetic Flow Meter Manufacturers in Jalandhar

    Electromagnetic Flow Meter Manufacturers in Patiala

    Electromagnetic Flow Meter Manufacturers in Bengaluru

    Electromagnetic Flow Meter Manufacturers in Mysore

    Electromagnetic Flow Meter Manufacturers in Vijayawada

    Electromagnetic Flow Meter Manufacturers in Chennai

    Electromagnetic Flow Meter Manufacturers in Coimbatore

    Electromagnetic Flow Meter Manufacturers in Madurai

    Electromagnetic Flow Meter Manufacturers in Hyderabad

    Electromagnetic Flow Meter Manufacturers in Raipur

    Electromagnetic Flow Meter Manufacturers in Ranchi

    Electromagnetic Flow Meter Manufacturers in Dhanbad

    For more read our blogs:- https://caramellaapp.com/itechflow/wZMeZxlpu/electromagnetic-flow-meter-manufacturers-in-ghaziabad

    0 comments No comments

  2. Michell 45 Reputation points
    2023-08-08T16:50:40.0733333+00:00

    Hui Liu-MSFT, Thank you for reply. It worked!!

    Also Iwould like to appreciate Brian Zarb for help and reponse.

    0 comments No comments