数据绑定在xaml中不起作用

JET*_*SAI 4 data-binding wpf xaml

我尝试使用绑定在Text内容中显示Hi.但是,单击该按钮时,它不起作用.有人可以帮我解决问题吗?谢谢.

1.XAML代码:

<Window x:Class="Wpftest.binding.Window0"                          
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window0" Height="300" Width="300">
   <Grid>
      <TextBox x:Name="textBox2" VerticalAlignment="Top" Width="168" 
               Text="{Binding Source= stu,  Path= Name, Mode=TwoWay}"/>
   </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

2.Class:

namespace Wpftest.binding.Model
{
   public class student : INotifyPropertyChanged 
   {
      public event PropertyChangedEventHandler PropertyChanged;        
      private string name;

      public string Name
      {
         get { return name; }

         set { name = value;

              if(this.PropertyChanged != null)
              {
                 this.PropertyChanged.Invoke(this, new     
                 PropertyChangedEventArgs("Name"));
              }
         }
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

3.XAML.cs:

 namespace Wpftest.binding
    {
        public partial class Window0 : Window
        {
            student stu;
            public Window0()
            {
                InitializeComponent();
                stu = new student();
           }

            private void button_Click(object sender, RoutedEventArgs e)
            {
                stu.Name += "Hi!";
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 6

有很多方法可以达到你的需要; 在正确的方法取决于您要创建什么风格的应用程序非常多.我将演示两种方法,这些方法需要对您提供的示例进行最少的更改:

方法1

设置DataContextstu并绑定到该Name属性.

XAML.cs

    private student stu;

    public Window0()
    {
        InitializeComponent();
        stu = new student();
        DataContext = stu;
    }
Run Code Online (Sandbox Code Playgroud)

XAML代码

<TextBox Text="{Binding Path=Name, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)

方法2

通常,您将设置DataContext除Window之外的某个对象(例如,如果您遵循MVVM模式,则为ViewModel),但有时您可能需要将控件绑定到Window的某些属性.在这种情况下,DataContext不能使用,但您仍然可以使用绑定到Window的属性RelativeSource.见下文:

XAML.cs

    // note this must be a property, not a field
    public student stu { get; set; }

    public Window0()
    {
        InitializeComponent();
        stu = new student();
    }
Run Code Online (Sandbox Code Playgroud)

XAML代码

<TextBox Text="{Binding Path=stu.Name, Mode=TwoWay, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
Run Code Online (Sandbox Code Playgroud)

提示:如果您遇到WPF数据绑定问题,那么查看调试器输出窗口以查看绑定跟踪消息通常会有所帮助.通过将此命名空间添加到Window元素,可以进一步增强调试功能

xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Run Code Online (Sandbox Code Playgroud)

然后设置TraceLevel例如

<TextBox Text="{Binding Source=stu, diag:PresentationTraceSources.TraceLevel=High}"/>
Run Code Online (Sandbox Code Playgroud)