如何更新`ObservableCollection <t>`所选项目?

时间:2018-08-16 10:11:27

标签: c# wpf mvvm

XAML:

<ListBox ItemsSource="{Binding VentuzCollection, Mode=TwoWay}" SelectedItem="{Binding SelectedVentuzCollection, Mode=TwoWay}" ItemTemplate="{StaticResource DataTemplateVentuzCollection}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" Height="115" VerticalAlignment="Top" Width="116"/>
<ListBox ItemsSource="{Binding SelectedVentuzCollection.VentuzData, Mode=TwoWay}" HorizontalAlignment="Left" Height="126" VerticalAlignment="Top" Width="122" Margin="168,164,0,0" ItemTemplate="{StaticResource DataTemplateVentuzDataCollection}" />

C#:

private static ObservableCollection<VentuzSocialManager> _ventuzCollection;
public ObservableCollection<VentuzSocialManager> VentuzCollection
{
    get => _ventuzCollection;
    set
    {
        if (_ventuzCollection == value) return;
        _ventuzCollection = value;
        OnPropertyChanged();
    }
 }

private static VentuzSocialManager _selectedventuzCollection;
public VentuzSocialManager SelectedVentuzCollection
{
    get => _selectedventuzCollection;
    set
    {
        if (_selectedventuzCollection == value) return;
        _selectedventuzCollection = value;
        OnPropertyChanged();
    }
 }

public class VentuzSocialManager:ViewModelBase
{
    public  string Id { get; set; }
    private static ObservableCollection<VentuzSocial> _ventuzData;
    public ObservableCollection<VentuzSocial> VentuzData
    {
        get => _ventuzData;
        set
        {
            if (_ventuzData == value) return;
            _ventuzData = value;
            OnPropertyChanged();
        }
    }
}

我使用VentuzDataViewModel.This.SelectedVentuzCollection?.VentuzData?.Add(exportSocial);更新了所选项目,但是当我使用此语句时,它更新了VentuzCollection中的所有对象。我想做的是,当在第一个列表框中选择一个项目时,我添加到第二个Listbox的任何内容都仅在第一个Listbox的选定项目中更新。

1 个答案:

答案 0 :(得分:1)

您必须从

中删除static
private static ObservableCollection<VentuzSocial> _ventuzData;

如果您想为每个ObservableCollection<VentuzSocial>对象拥有一个VentuzSocialManager实例,否则将拥有您所拥有的-所有ObservableCollection<VentuzSocial>对象拥有一个VentuzSocialManager实例