Chris Chris - 28 days ago 13
C# Question

C# WPF MVVM, Getting two instances of main object

I am completely new to WPF and MVVM, I am trying to link a property to a textbox on a WPF form. However, I seem to be getting two instances of the main object, which causes -1 exit error. I think this is caused by the class and DataContext dependencies in the XAML file.

Can anyone point me in the right direction as to why this might be?

The main part of my XAML includes:

<Window
x:Class="MyProg.MainWindowViewModel"
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:MyProg"
xmlns:vm="clr-namespace:MyProg"
mc:Ignorable="d"
Title="MainWindow" Height="572" Width="855" WindowStartupLocation="CenterScreen" >

<Window.Resources>
<vm:MainWindowViewModel x:Key="viewModel" />
</Window.Resources>

<Grid DataContext="{StaticResource ResourceKey=viewModel}">
<TextBox x:Name="textBox"
Text="{Binding FormTextBox}" />
</Grid>
</Window>


My Model includes:

namespace MyProg
{
public class MyProgModel : INotifyPropertyChanged
{
private string _textBox; // holds contents of text box

public string MyTextBox
{
get { return _textBox; }

set
{
_textBox = value;
Console.WriteLine(_textBox);
OnPropertyChanged("MyTextBox");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
Console.WriteLine("Keyboard Model OnPropertyChanged {0}", propertyName);

if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}


and View Model:

namespace MyProg
{
public partial class MyProg : Window, INotifyPropertyChanged
{
private MyProgModel _mainWindowModel;

private string _textBox = "Pan Galactic Gargle Blaster"; // holds contents of text box

public MainWindowViewModel()
{
_mainWindowModel = new MyProgModel
{ // Instantiate and initialise _mainWindowModel
MyTextBox = "Hello from me"
};
}

public string FormTextBox
{
get { return _textBox; }

set
{
_textBox = value;
OnPropertyChanged("FormTextBox");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
Console.WriteLine("View model OnPropertyChanged {0}", propertyName);

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Answer Source

Your viewmodel is simultaneously a view - separate them, otherwise you have a reversive call in window resources(that you need for DataContext)