数据绑定在XAML中无法工作。

5
我尝试使用绑定在文本内容中显示“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.班级:
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!";
            }
        }
    }

你能展示一下 stu 是什么吗? - StepUp
将DataContext的赋值添加到您的ViewModel中。 - Theodosius Von Richthofen
2个回答

6

有很多方法可以实现您所需的功能;正确的方法非常取决于您想创建什么样的应用程序。我将演示两种方法,这两种方法将需要对您提供的示例进行最少的更改:

方法一

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

XAML.cs

    private student stu;

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

XAML 代码

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

方法二

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

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}"/>

嗨,Rob:感谢您的帮助。不过,我还有一个问题。为什么XAML.cs中的代码仍然可以工作,而不是使用DataContext?XAML.cs中的代码如下所示:Binding bind = new Binding(); bind.Source = stu; bind.Path = new PropertyPath("Name"); this.textBox2_Copy.SetBinding(TextBox.TextProperty, bind); - JET TSAI
嗨@JETTSAI。在XAML中声明绑定与在C#中直接创建绑定有些不同。XAML绑定使用BindingExtension类将"{Binding xxx}"声明转换为绑定,而正是这个类解释了你的Source=stu。实际上,它将stu解释为字符串字面量"stu"。 - Rob
嗨,罗布:谢谢你的解释。 - JET TSAI

3

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

public MainWindow()
{
   DataContext=new YourViewModel();
}

WindowDataContext是在View(XAML)和ViewModel(C#代码)之间进行通信的一种方式。

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

<Window.DataContext>
  <local:YourViewModel/>
</Window.DataContext>

此外,与其处理 Click 事件,你应该使用 ButtonCommand 属性。可查看此处的示例

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接