繁体   English   中英

更改数据上下文后,依赖项属性不会更新

[英]Dependency Property won't update after changing 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时,绑定似乎丢失了。

我想念什么?

我试图按照您在帖子中的描述进行操作,但是真诚的我没有发现问题。 在我测试过的所有情况下,我的项目都能完美运行。 我不喜欢您的解决方案,因为我认为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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM