当我在 XAML 中声明数据上下文时,它不起作用。但是如果在代码中设置,同样的工作。
详细分析。
我的 XAML
<Window x:Class="SimpleDatabindingwithclass.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" Name="windo">
<Grid DataContext="{Binding ElementName=windo,Path=objectOfStudent}">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Margin="25" Height="25" Width="100" HorizontalAlignment="Left" Name="TextBox1" Text="{Binding Path=StudentName}"></TextBox>
</Grid>
</Window>
对应的代码。
namespace SimpleDatabindingwithclass
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Student objectOfStudent = new Student();
objectOfStudent.StudentName = "John diley";
objectOfStudent.Address = "20, North Travilia, Washington DC.";
//not setting datacontext here since i set that in xaml
}
public class Student
{
private string studentname;
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
public string StudentName
{
get{return studentname;}
set{studentname = value;}
}
}
}
}
但是,当我使用此 XAML 并通过代码设置 datacontext 时,它同样有效!
即,当我把类似的东西
this.DataContext = objectOfStudent;
在 MainWindow() 中,应用程序工作!你认为问题是什么?