Zephylir Zephylir - 27 days ago 11
C# Question

WPF Binding to object created within MainWindow class

So I need to bind a simple label to property of an object created from class. The Class that I am trying to create goes like this:

public class Creature : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private string _Name = "Default";
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged(nameof(Name));
}
}
private string _Gender = "Default";
public string Gender
{
get { return _Gender; }
set
{
if (_Gender != value)
{
_Gender = value;
OnPropertyChanged(nameof(Gender));
}
}
}
}


Then I create instance of it in the MainWindow.xaml.cs like this:

public partial class MainWindow : Window
{
private Creature Player = new Creature();
public MainWindow()
{
InitializeComponent();
//Tried setting DataContext in hopes of being able to access Player object
DataContext = this;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Player.Gender = "Male";
Player.Name = "Mike";
//This bit of code here is used to check if value has changed by displaying it in a textbox
textBox.Text = "Name: " + Player.Name;
textBox.Text += "\nGender: " + Player.Gender;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
Player.Gender = "Female";
Player.Name = "Sarah";
textBox.Text = "Name: " + Player.Name;
textBox.Text += "\nGender: " + Player.Gender;
}
}


The problem is I don't know what is supposed to be DataContext here, as no matter what I tried I can't get access to Player field, and I tried setting it to public, didn't change anything. I still can bind to the class "Creature" but not the field, is there a way to make changes done to field Creature, apply to the class perhaps?

Answer

Just assign your class instance to the DataContext in your MainWindow constructor:

public Creature player;
public MainWindow()
{
    InitializeComponent();
    player = new Creature();
    this.DataContext = player;
}

this stands for current instance, so in your example it refers to class MainWindow

Comments