无法通过XAML设置DataContext,但可以通过代码设置相同的内容

时间:2012-08-08 10:01:03

标签: c# wpf xaml datacontext

当我在XAML中声明它时,Datacontext不起作用。但是如果在Code中设置,则同样有效。

详细分析。

我的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&amp;通过代码设置datacontext,它可以工作!

即,当我提出像

这样的东西时
     this.DataContext = objectOfStudent; 

在MainWindow()中,应用程序正常工作! 您认为问题是什么?

2 个答案:

答案 0 :(得分:3)

绑定仅适用于公共属性,不能绑定到某个局部变量。将objectOfStudent设为MainWindow的公共财产。

编辑:

public Student objectOfStudent { get; set; }

public MainWindow()
{
    InitializeComponent();
    objectOfStudent = new Student();
    objectOfStudent.StudentName = "John diley";
    objectOfStudent.Address = "20, North Travilia, Washington DC.";
    //not setting datacontext here since i set that in xaml
 }

编辑:

此外,您需要在MainWindowStudent类中实施INotifyPropertyChanged界面,并在设置属性时引发PropertyChanged。这是正确的方法,每次更改属性时都会更新绑定。或者一种简单的方法:在调用objectOfStudent之前创建InitializeComponent

public MainWindow()
{
    objectOfStudent = new Student();
    objectOfStudent.StudentName = "John diley";
    objectOfStudent.Address = "20, North Travilia, Washington DC.";
    InitializeComponent();
    //not setting datacontext here since i set that in xaml
 }

答案 1 :(得分:2)

这是因为您尝试通过XAML使用名为objectOfStudent局部变量 - 这在XAML的上下文中没有意义。 XAML只接受字段和属性,而不接受局部变量。