My code:
XAML:
<Window x:Class="BindingTut.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBox Text="{Binding FirstName}"/>
<Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
</StackPanel>
</Grid>
</Window>
Customer class:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Code behind:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private int index = 0;
public Customer Tmp;
List<Customer> ar = new List<Customer>();
public MainWindow()
{
InitializeComponent();
ar.Add(new Customer { FirstName = "qwe", LastName = "rty" });
ar.Add(new Customer { FirstName = "asd", LastName = "asd" });
this.Tmp = ar[index];
this.DataContext = this.Tmp;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.Tmp = ar[++index];
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Tmp"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
So when application loads, everything is fine – textbox shows “qwe”, but button, which should load second customer object doesn’t work. What am I doing wrong?
You’re not changing the
DataContext. You’re changing the value in the property that you set theDataContextto.You don’t need a
Tmpproperty at all. Just change theDataContextin your event handler, e.g.: