WPF绑定到MainWindow类中创建的对象

时间:2016-11-05 17:45:29

标签: c# wpf xaml object data-binding

所以我需要将一个简单的标签绑定到从class创建的对象的属性。我想要创建的类是这样的:

    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));
            }
        }
    }
}

然后我在MainWindow.xaml.cs中创建它的实例,如下所示:

    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;
    }
}

问题是我不知道这里应该是什么DataContext,因为无论我尝试什么,我都无法访问Player字段,我尝试将其设置为公开,没有改变任何东西。我仍然可以绑定到类“生物”而不是字段,有没有办法对字段Creature进行更改,也许适用于该类?

1 个答案:

答案 0 :(得分:1)

只需将您的班级实例分配到DataContext构造函数中的MainWindow

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

this代表当前实例,因此在您的示例中它指的是类MainWindow