5

I try to use binding to display Hi in the Text content. However, when clicking the button, it doesn't work. Could someone help me to solve the problem? Thanks.

1.XAML CODE :

<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!";
            }
        }
    }
StepUp
  • 36,391
  • 15
  • 88
  • 148
JET TSAI
  • 97
  • 2
  • 6

2 Answers2

6

There are many ways to achieve what you need; the correct method depends very much on what style of application you want to create. I'll demonstrate two methods that will require minimal changes from your supplied example:

Method 1

Set the DataContext to stu and bind to the Name property.

XAML.cs

    private student stu;

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

XAML code

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

Method 2

Generally you will set the DataContext to some object other than the Window (e.g. the ViewModel if you are following the MVVM pattern), but sometimes you may need to bind a control to some property of the Window. In this case the DataContext can't be used, but you can still bind to a property of the Window by using RelativeSource. See below:

XAML.cs

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

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

XAML code

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

Hint: if you are having trouble with WPF data binding, then it often helps to look at the debugger output window to see the binding trace messages. And debugging can be further enhanced by adding this namespace to the Window element

xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"

and then setting the TraceLevel e.g.

<TextBox Text="{Binding Source=stu, diag:PresentationTraceSources.TraceLevel=High}"/>
Rob
  • 1,472
  • 12
  • 24
  • Hi, Rob: Thanks for your help. However, I have an another Question. Why the code in XAML.cs can still work instead of using DataContext? the code in XAML.cs as followed: Binding bind = new Binding(); bind.Source = stu; bind.Path = new PropertyPath("Name"); this.textBox2_Copy.SetBinding(TextBox.TextProperty, bind); – JET TSAI May 23 '16 at 03:06
  • Hi @JETTSAI. Declaring the binding in XAML is a little different to programmatically creating a binding directly in C#. A XAML binding uses the BindingExtension class to translate the "{Binding xxx}" declaration into a Binding, and it is this class that interprets your `Source=stu`. Actually it interprets `stu` as the string literal "stu". – Rob May 23 '16 at 08:55
  • Hi, Rob: Thanks for your explanation. – JET TSAI May 24 '16 at 02:34
3

Basically you need to set DataContext property to your Window. For example:

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

DataContext of Window is a way to communicate between View(XAML) and ViewModel(C# code)

In addition, you can add DataContext in xaml:

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

Also, instead of handling Click event, you should use Command property of Button. Example can be seen here.

Community
  • 1
  • 1
StepUp
  • 36,391
  • 15
  • 88
  • 148