2012-03-31 117 views
2

我有一个WPF文本框与datacontext的绑定。更改数据环境后,依赖项属性不会更新

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

我设置在文本框中的容器控制的代码的datacontext(TabItem的在这种情况下)

tiMaterial.DataContext = _materials[0]; 

我也有与其他材料列表框。我想更新文本字段,被选择的另一种材料时,因此我的代码:

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> 
相关问题