将ObservableCollection绑定到多个列表视图不起作用

时间:2019-03-28 08:37:52

标签: c# wpf listview mvvm observablecollection

我是编程新手,在弄清楚如何使我的ObservableCollection在WPF中的两个不同Windows上的两个不同列表视图上工作时遇到了麻烦。我认为问题在于我是如何实现ObservableCollection的,而罪魁祸首是此行,如SoundsWindow类所示:

ViewModel vm = this.DataContext as ViewModel;

这是我的列表视图显示通过以下方式添加的项目的方式:

vm.AddFile(fi.Name, file, 1);

问题在于这不会更新另一个窗口上的另一个列表视图,也不存储任何内容。

这里是我的ViewModel:

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        SoundFiles = new ObservableCollection<SoundFile>();
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        handler(this, new PropertyChangedEventArgs(name));
    }

    public void AddFile(string fileName, string fileLocation, int groupID)
    {
        SoundFile soundfile = new SoundFile { FileName = fileName, FileLocation = fileLocation, GroupID = groupID };
        SoundFiles.Add(soundfile);
    }

    private ObservableCollection<SoundFile> soundfiles;
    public ObservableCollection<SoundFile> SoundFiles
    {
        get { return soundfiles; }
        set
        {
            soundfiles = value;
            OnPropertyChanged("SoundFiles");
        }
    }
}

SoundsWindow类:

public partial class SoundsWindow : Window
{
    public SoundsWindow()
    {
        InitializeComponent();

        this.DataContext = new ViewModel();

    }

    private void loadFileBtn1_Click(object sender, RoutedEventArgs e)
    {
        var ofd = new OpenFileDialog();
        ofd.Multiselect = true;
        ofd.Filter = "MP3 Files (*.mp3)|*.mp3";
        var result = ofd.ShowDialog();

        if (result == true)
        {
            ViewModel vm = this.DataContext as ViewModel;

            foreach (String file in ofd.FileNames)
            {
                FileInfo fi = new FileInfo(file);                   
                vm.AddFile(fi.Name, file, 1);
            }               
        }
    }

我的SoundFile类:

public class SoundFile
{
    public string FileName { get; set; }
    public string FileLocation { get; set; }
    public int GroupID { get; set; }
}

还有xaml:

<ListView x:Name="FilesList1" ItemsSource="{Binding SoundFiles}" HorizontalAlignment="Left" Height="379" Margin="10,35,0,0" VerticalAlignment="Top" Width="600">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FileName}" Width="230"/>
                <GridViewColumn Header="Location" DisplayMemberBinding="{Binding Path=FileLocation}" Width="320"/>
                <GridViewColumn Header="Group" DisplayMemberBinding="{Binding Path=GroupID}" Width="40"/>
            </GridView>
        </ListView.View>
    </ListView>

出于测试目的,另一个窗口是SoundsWindow的副本,因此应该不成问题。

由于我几乎不知道我在做什么,iv检查了所有内容,但是可以肯定的罪魁祸首是我对如何在ObservableCollection中添加和存储内容的实现。任何帮助将不胜感激。

0 个答案:

没有答案
相关问题