I am building a website from the standard Silverlight Navigation Application in VS2012. I would like to have the same datacontext for my Mainpage-view and my Home-view. I have created an Employee class with one property, Name, which i would like to show in a textblock on the navigation in the mainpage-view and in the content of the home-view. In the home-view i will also have a textblock, from where i can change the content of name.
No matter how i try to set the datacontext it always create an instance of employee for each of the two views. How do i make them use the same instance?
Employee.cs
public class Employee : INotifyPropertyChanged
{
string _name = "Test";
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainPage.xaml
<TextBlock x:Name="ApplicationNameTextBlock" Style="{StaticResource ApplicationNameStyle}"
Text="{Binding Name}"/>
Home.xaml
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
<TextBlock Text="{Binding Name}"/>
This can be a achieved with a helper class that is often called a ViewModelLocator
.
public static class ViewModelLocator
{
private static Employee myEmployee = null;
public static Employee GetEmployee()
{
if (myEmployee == null)
myEmployee = new Employee();
return myEmployee;
}
}
In code behind of your pages:
DataContext = ViewModelLocator.GetEmployee();