我有以下代码,我试图显示我的数据上下文的属性。 但是我运行应用程序时什么也看不到。 我是WPF的初学者。 我可能在某处丢失了一些小设置。DataTemplate没有绘制,wpf
如果我删除DataContext="{Binding RelativeSource={RelativeSource Self}}"
并在后面的代码设置的DataContext到MyPerson属性和设置
<ContentControl x:Name="myCC" Content="{Binding }"></ContentControl>
然后一切工作良好。
<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"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Person}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition Width="200"></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 x:Name="myCC" Content="{Binding Path=MyPerson}"></ContentControl>
</Grid>
</Window>
public partial class MainWindow : Window
{
public Person MyPerson { get; set; }
public MainWindow()
{
InitializeComponent();
MyPerson = new Person { Age = 30, Name = "David" };
}
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));
}
}
}
尝试设置上面的InitializeComponent(); MyPerson属性; – 2014-11-24 11:52:41
因为你是wpf的初学者。请看看[MVVM模式](http://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level) – 2014-11-24 11:58:12