c# - WPF Binding to object created within MainWindow class -
so need bind simple label property of object created class. class trying create goes 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 { { return _name; } set { _name = value; onpropertychanged(nameof(name)); } } private string _gender = "default"; public string gender { { return _gender; } set { if (_gender != value) { _gender = value; onpropertychanged(nameof(gender)); } } } }
then create instance of in mainwindow.xaml.cs this:
public partial class mainwindow : window { private creature player = new creature(); public mainwindow() { initializecomponent(); //tried setting datacontext in hopes of being able access player object datacontext = this; } private void button1_click(object sender, routedeventargs e) { player.gender = "male"; player.name = "mike"; //this bit of code here used check if value has changed displaying in 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 don't know supposed datacontext here, no matter tried can't access player field, , tried setting public, didn't change anything. still can bind class "creature" not field, there way make changes done field creature, apply class perhaps?
just assign class instance datacontext
in mainwindow
constructor:
public creature player; public mainwindow() { initializecomponent(); player = new creature(); this.datacontext = player; }
this
stands current instance, in example refers class mainwindow
Comments
Post a Comment