2012-03-31 115 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> 
相關問題