0

当我在 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() 中,应用程序工作!你认为问题是什么?

4

2 回答 2

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
 }

编辑:

Also you need to implement INotifyPropertyChanged interface in the MainWindow and Student classes and raise PropertyChanged when you set the properties. That is the right way, the binding will be updated everytime you change the properties. Or a simple way: create objectOfStudent before calling 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
 }
于 2012-08-08T10:14:45.990 回答
2

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

于 2012-08-08T10:04:22.223 回答