2011-07-24 8 views
2

私のコード変更した場合:後ろデータバインディング、リフレッシュデータのDataContextは

public class Customer 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

コード: 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クラスを

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"と表示されますが、2番目の顧客オブジェクトを読み込むボタンは機能しません。私は間違って何をしていますか?

答えて

0

あなたはDataContextを変更していません。 DataContextに設定したプロパティの値を変更しています。

Tmpプロパティはまったく必要ありません。イベントハンドラのDataContextを変更してください。例:

DataContext = ar[++index]; 
+0

はい、それは動作します..しかし、何のINotifyPropertyChangedですか? Tmpはプロパティで、私はそれを変更するので、UIを更新する必要がありますか? –

+0

@bah - いいえ、あなたが持っているものはTmpに "バインド"されていないので、それを変更してもUIには影響しません。 DataContextをTmp(これは 'qwe')と同じ参照に設定する' this.DataContext = this.Tmp'をいつ行うのですか?したがって、Tmpを変更してもDataContextには影響しません。 – CodeNaked

+0

ああ、これは今のところできます。私にはたくさんのことが学べるようです。 –

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 }); 
} 
+0

しかし、どうしてそういうのですか?プロパティが値自体を保持できるのはなぜですか? –

+0

@bah - DataContextは一度しか設定しないので、決して更新されません。それをTmpプロパティにバインドすると、Tmpを変更するたびにDataContextも変更されます。 – CodeNaked

関連する問題