RaisePropertyChanged不更新UI

时间:2018-12-20 19:23:45

标签: c# wpf xaml observablecollection

RaisePropertyChanged在调用后不会更新UI中的列表框。 最初,在打开应用程序时,将进行更新并填充列表。在我调用ViewModel(TracksVM)的构造函数后,该构造函数触发了更新ObservableCollection的方法,然后由setter填充集合,但是RaisePropertyChanged似乎对盒子没有影响。

已解决:
正如Clemens所建议的那样,我有2个ViewModel类的实例,因此,由于新列表已移至第二个实例,因此列表框无法采用新创建的Tracks列表。在同一对象实例上运行更新代码后,列表框便开始相应地更新。 XAML:

<ListBox Name="DownloadsBox" ItemsSource="{Binding Tracks}" SelectedItem="{Binding SelectedTrack}" Margin="10,10,10,10" DockPanel.Dock="Top" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="TracksListBox_SelectionChanged">
    <ListBox.ItemTemplate>
       <DataTemplate>
           <TextBlock Text="{Binding FileName}"/>
       </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ViewModel:

public class TracksVM:INotifyPropertyChanged
{
    private FileManager fm;
    private ObservableCollection<Track> _tracks;

    public ObservableCollection<Track> Tracks
    {
        get => _tracks;
        set
        {
            _tracks = value; RaisePropertyChanged("Tracks");
        }
    }

    private ObservableCollection<string> _genres;
    public ObservableCollection<string> Genres
    {
        get => _genres;
        set { _genres = value;  RaisePropertyChanged("Genres"); }
    }
    private Track _selectedTrack;
    public Track SelectedTrack
    {
        get => _selectedTrack;
        set
        {
            _selectedTrack = value; RaisePropertyChanged("SelectedTrack");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    public TracksVM()
    {
        fm = new FileManager();
        LoadData();
    }
    void LoadData()
    {
        Console.WriteLine("Loading Tracks in Download box");
        Tracks = fm.ListOfTracks(ConfigurationManager.DownloadsDirectory).ToObservableCollection();
        Genres = ConfigurationManager.Genres.ToObservableCollection();
    }
}

ViewModel的触发和ObservableCollection的更新:

 TracksVM tVM;
 internal void MoveTrack(string fileTobeMoved,string folderLocation)
    {

        Console.WriteLine($"Track: {fileTobeMoved}, location: {folderLocation}");
        try
        {

            File.Move(fileTobeMoved, folderLocation);
            tVM = new TracksVM();

        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

1 个答案:

答案 0 :(得分:0)

正如Clemens所建议的,我有2个ViewModel类的实例,因此,由于新列表已移至第二个实例,因此列表框无法采用新创建的Tracks列表。在同一对象实例上运行更新代码后,列表框便开始相应更新。