更改datacontext后,依赖属性不会更新

时间:2012-03-31 01:23:19

标签: c# wpf binding datacontext

我有一个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 个答案:

答案 0 :(得分: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>