Change property of class 1 from class 2 using MVVM

Sarah 186 Reputation points
2022-12-01T11:13:37.157+00:00

I am trying to change the property "MyText" of the class "MainViewModel" from the class "ClassA" under MVVM. For this I use the classes as singleton. Unfortunately it does not work for me. It should be a simple call. Does anyone have any idea what might be doing wrong?

<Window x:Class="MoreClasses.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:MoreClasses"  
        mc:Ignorable="d"  
        Title="MainWindow" Height="450" Width="800">  
  
    <Window.DataContext>  
        <local:MainViewModel/>  
    </Window.DataContext>  
    <Grid>  
        <StackPanel Orientation="Vertical">  
            <TextBlock Text="{Binding MyText}"  
                       Margin="50"/>  
            <Button Content="Main Class"  
                    Width="150"  
                    Height="70"  
                    Margin="50"  
                    Command="{Binding Cmd}"  
                    CommandParameter="MainClass"/>  
  
            <Button Content="Class A"  
                    Width="150"  
                    Height="70"  
                    Command="{Binding Cmd}"  
                    CommandParameter="ClassA" />  
        </StackPanel>  
    </Grid>  
</Window>  


namespace MoreClasses  
{  
    public class MainViewModel : BaseViewModel  
    {  
        #region Singelton  
        private static MainViewModel instance;  
  
        static MainViewModel()  
        {  
            instance = new MainViewModel();  
        }  
  
        public static MainViewModel Instance  
        {  
            get => instance;  
        }  
        #endregion Singelton  
  
        private string myText = string.Empty;  
        public string MyText  
        {  
            get  
            {  
                return myText;  
            }  
            set  
            {  
                myText = value;  
                OnPropertyChanged();  
            }  
        }  
  
        public RelayCommand Cmd { get => new RelayCommand(CmdExec); }  
        private void CmdExec(object parameter)  
        {  
            switch (parameter.ToString())  
            {  
                case "MainClass":  
                    try  
                    {  
                        MyText = "I am from Class -> MainViewModel!";  
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.Message);  
                    }  
                    break;  
  
                case "ClassA":  
                    try  
                    {  
                        ClassA.Instance.ChangeText();  
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.Message);  
                    }  
                    break;  
  
                default:  
                    break;  
            }  
        }  
    }  
}  


namespace MoreClasses  
{  
    public class ClassA  
    {  
  
        #region Singelton  
        private static ClassA instance;  
  
        static ClassA()  
        {  
            instance = new ClassA();  
        }  
  
        public static ClassA Instance  
        {  
            get => instance;  
        }  
        #endregion Singelton  
  
        public void ChangeText()  
        {  
            MainViewModel.Instance.MyText = "I'am from Class -> ClassA!";  
        }  
    }  
}  
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,674 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2022-12-01T18:41:18.197+00:00

    Hi Sarah,
    please, change your code to use only one instance of MainViewModel:

     namespace MoreClasses  
     {  
         public class MainViewModel : BaseViewModel  
         {  
             #region Singelton  
             private static MainViewModel instance;  
          
             public MainViewModel()  
             {  
                 instance = this;  
             }  
          
             public static MainViewModel Instance  
             {  
                 get => instance;  
             }  
             #endregion Singelton  
    ...  
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Newest
  1. Hui Liu-MSFT 38,256 Reputation points Microsoft Vendor
    2022-12-05T08:21:37.733+00:00

    You could provide classes with private constructors to ensure that only one instance of a class can be created.

    267123-singleton.txt

    Get rid of

    <Window.DataContext>  
         <local:MainViewModel/>  
     </Window.DataContext>   
    

    Because DataContext is set to another instance of MainViewModel.

    Method 1:

     public MainWindow()  
        {  
            InitializeComponent();  
            DataContext = MainViewModel.Instance;  
        }  
    

    or Method 2:

    <Window ...  
            DataContext="{x:Static local:MainViewModel.Instance}">  
    

    ----------------------------------------------------------------------------

    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 person found this answer helpful.