我的問題是,我添加了2個對象的類型文件(出於測試的原因)在Viewmodel這是一個observablecollection,但視圖不會更新與啓動的應用。 這裏是Mainview.cs:MVVM ListView與Viewmodel的Observable Collection類型不更新視圖
public class MainView:ObservableCollection<Files>
{
public MainView()
{
Files x = new Files("picture", "jpg");
Files x1 = new Files("soundfile", "mp3");
Add(x);
Add(x1);
}}
我做了什麼錯?以及如何避免這個錯誤?如果我不更改Files類中的屬性,並且只想在創建新的File對象時更新視圖,那麼是否真的需要INotifyPropertyChanged?
我得到了這個類:
public class Files:INotifyPropertyChanged
{
private String _fileName;
public String FileName
{
get { return _fileName; }
set { _fileName = value; OnPropertyChanged("FileName"); }
}
private String _dataType;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public String DataType
{
get { return _dataType; }
set { _dataType = value; OnPropertyChanged("DataType"); }
}
public Files(string filename, string dataType)
{
this._fileName = filename;
this._dataType = dataType;
}
}
而這個視圖模型:
public class MainView:ObservableCollection<Files>
{
public MainView()
{
Files x = new Files("picture", "jpg");
Files x1 = new Files("soundfile", "mp3");
Add(x);
Add(x1);
}
}
而且在XAML這樣做:
<Window x:Class="ClientTestDesign.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ClientTestDesign"
xmlns:vm="clr-namespace:ClientTestDesign.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
>
<Window.Resources>
<vm:MainView x:Key="View"></vm:MainView>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="75"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Style="{DynamicResource ForwardBackButton}" Content="Back"></Button>
<Button Grid.Column="1" Style="{DynamicResource StopButton}" Content="Pause"></Button>
<Button Grid.Column="2" Style="{DynamicResource ForwardBackButton}" Content="Forward"></Button>
<ListView Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.ColumnSpan="3">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding /FileName, Source={StaticResource View}}"></TextBlock>
<TextBlock Text="{Binding /FileName, Source={StaticResource View}}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
這更是一個認識問題。你的'Files'類應該是你的ViewModel。 'Files'應該是ViewModel中的一個屬性。 –
@KosalaW你的意思是文件應該是可觀察的集合?我的fviewmodel應該包含文件的屬性? –
@KosalaW這不可能是唯一的錯誤,可以嗎?我改變它沒有工作 –