JET TSAI
JET TSAI

Reputation: 97

Data Binding doesn't work in xaml

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

Upvotes: 5

Views: 6021

Answers (2)

Rob
Rob

Reputation: 1492

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

Upvotes: 6

StepUp
StepUp

Reputation: 38094

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.

Upvotes: 3

Related Questions