2012-03-31 4 views
2

datacontext에 바인딩 된 WPF 텍스트 상자가 있습니다. datacontext를 변경 한 후에 종속성 속성이 업데이트되지 않습니다.

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

는 제가 다른 물질과의리스트 박스가

tiMaterial.DataContext = _materials[0]; 

(이 경우 TabItem의) 텍스트 박스의 컨테이너 제어 코드의 데이터 컨텍스트를 설정.

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> 
관련 문제