2012-03-31 24 views
2

datacontextへのバインディングを持つWPFテキストボックスがあります。 データコンテキストを変更した後に依存関係プロパティが更新されない

<TextBox Grid.Column="1" Grid.Row="4" Text="{Binding Path=Density,UpdateSourceTrigger=PropertyChanged}"/> 

は、私はまた、他の材料とリストボックスを有する

tiMaterial.DataContext = _materials[0]; 

(この場合のTabItem)テキストボックスのコンテナコントロールのコードでのDataContextを設定します。

private void lbMaterials_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) 
{ 
    _material = (Material) lbMaterials.SelectedValue; 
    tiMaterial.DataContext = _material;    
} 

MaterialクラスがINotifyPropertyChangedインターフェイスを実装します。他の材料が選択されているとき、私はので、私はコード、テキストフィールドを更新します。私は双方向の更新作業をしている、それはちょうど私がDataContextを変更すると、バインディングが失われているようだ。

私には何が欠けていますか?

答えて

1

私はあなたの記事で説明したことをしようとしましたが、誠実に私は問題を見つけられませんでした。私がテストしたすべてのケースで、私のプロジェクトは完璧に機能します。 私はMVVMがより明確だと思うのであなたの解決策が嫌いですが、あなたのやり方もうまくいきます。

私はこれがあなたを助けてくれることを願っています。

public class Material 
{ 
    public string Name { get; set; }  
} 

public class ViewModel : INotifyPropertyChanged 
{ 
    public ViewModel() 
    { 
     Materials = new Material[] { new Material { Name = "M1" }, new Material { Name = "M2" }, new Material { Name = "M3" } }; 
    } 

    private Material[] _materials; 
    public Material[] Materials 
    { 
     get { return _materials; } 
     set { _materials = value; 
      NotifyPropertyChanged("Materials"); 
     } 
    } 

    #region INotifyPropertyChanged Members 
    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
    #endregion 
} 

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     DataContext = new ViewModel(); 
    } 

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     gridtext.DataContext = (lbox.SelectedItem); 
    } 
} 

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="auto" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 

    <Grid x:Name="gridtext"> 
     <TextBlock Text="{Binding Name}" /> 
    </Grid> 

    <ListBox x:Name="lbox" 
      Grid.Row="1" 
      ItemsSource="{Binding Materials}" 
      SelectionChanged="ListBox_SelectionChanged"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Name}" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 
関連する問題