数据绑定在xaml中不起作用

时间:2016-05-13 08:38:53

标签: wpf xaml data-binding

我尝试使用绑定在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>

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"));
              }
         }
       }
    }
}

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!";
            }
        }
    }

2 个答案:

答案 0 :(得分:6)

有很多方法可以达到你的需要; 正确的方法在很大程度上取决于您要创建的应用程序样式。我将演示两种方法,这些方法需要对您提供的示例进行最少的更改:

方法1

DataContext设置为stu并绑定到Name属性。

<强> XAML.cs

    private student stu;

    public Window0()
    {
        InitializeComponent();
        stu = new student();
        DataContext = stu;
    }

XAML代码

<TextBox Text="{Binding Path=Name, Mode=TwoWay}"/>

方法2

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

<强> XAML.cs

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

    public Window0()
    {
        InitializeComponent();
        stu = new student();
    }

XAML代码

<TextBox Text="{Binding Path=stu.Name, Mode=TwoWay, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>

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

,可以进一步增强调试功能
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"

然后设置TraceLevel,例如

<TextBox Text="{Binding Source=stu, diag:PresentationTraceSources.TraceLevel=High}"/>

答案 1 :(得分:4)

基本上,您需要将DataContext属性设置为Window。 例如:

public MainWindow()
{
   DataContext=new YourViewModel();
}
DataContext的{​​{1}} <{1}}是Window(XAML)和View之间通信的一种方式(C#代码)

此外,您可以在xaml中添加ViewModel

DataContext

此外,您应该使用<Window.DataContext> <local:YourViewModel/> </Window.DataContext> Click属性,而不是处理Command事件。 Example can be seen here