我刚刚开始使用WPF,但我的绑定不起作用 当我启动应用程序时,屏幕只是空白。
这是我的XAML
<Window x:Class="HelloWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ContentControl Content="{Binding PersonOne}" Width="auto" Height="auto" >
<ContentControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding FirstName}" FontSize="15" />
<TextBlock Text="{Binding Age}" FontSize="12" />
</StackPanel>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
</Grid>
这是代码:
public partial class MainWindow : Window
{
public Person PersonOne;
public MainWindow()
{
InitializeComponent();
PersonOne = new Person();
PersonOne.Gender = Gender.Female;
PersonOne.Age = 24;
PersonOne.FirstName = "Jane";
PersonOne.LastName = "Joe";
this.DataContext = this;
}
}
这是人类
public class Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
public enum Gender
{
Male,
Female
}
我做错了什么?
答案 0 :(得分:2)
您无法绑定到字段,只能绑定属性,因此请更改此项:
public Person PersonOne;
到此:
public Person PersonOne {get;set;}
顺便说一下,您可能需要创建一个ViewModel,而不是将数据放在Window本身。