我的代码: 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>
客户类:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
代码背后:
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;
}
因此,当应用程序加载时,一切都很好 - 文本框显示“qwe”,但是应该加载第二个客户对象的按钮不起作用。我做错了什么?
答案 0 :(得分:1)
您没有更改DataContext
。您正在更改将DataContext
设置为。
您根本不需要Tmp
属性。只需更改事件处理程序中的DataContext
,例如:
DataContext = ar[++index];
答案 1 :(得分:0)
你需要让Tmp成为一个属性,然后将DataContext绑定到它,就像这样;
private Customer tmp;
public Customer Tmp {
get {
return this.tmp;
}
set {
this.tmp = value;
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Tmp"));
}
}
public MainWindow()
{
InitializeComponent();
ar.Add(new Customer { FirstName = "qwe", LastName = "rty" });
ar.Add(new Customer { FirstName = "asd", LastName = "asd" });
this.Tmp = ar[index];
this.SetBinding(DataContextProperty, new Binding("Tmp") { Source = this });
}