我是WPF的新手,我有一个应用程序,我为自定义类型Person定义了一个datatemplate。 我在ContentControl中使用它,但我只看到我的类型Person的类型名称。 这是代码。
<Window x:Class="WpfTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTestApp"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="local:Person" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Content="_Name:" Grid.Row="0" Grid.Column="0"></Label>
<TextBox Text="{Binding Path=Name}" Grid.Column="1" Grid.Row="0"></TextBox>
<Label Content="_Age:" Grid.Row="1" Grid.Column="0"></Label>
<TextBox Text="{Binding Path=Age}" Grid.Column="1" Grid.Row="1"></TextBox>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid >
<ContentControl Content="{Binding }" >
</ContentControl>
</Grid>
</Window>
和....
public partial class MainWindow : Window
{
public Person _person {get;set;}
public MainWindow()
{
InitializeComponent();
_person = new Person { Age = 30, Name = "David" };
DataContext = _person;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button is clicked!!!");
}
}
public class Person : INotifyPropertyChanged
{
private int _age;
private string _name;
public int Age
{
get
{
return _age;
}
set
{
if (value != _age)
{
_age = value;
OnPropertyChanged("Age");
}
}
}
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}