【发布时间】:2019-10-25 14:14:34
【问题描述】:
我已经尝试了几个小时来让带有 ObservableCollection 的 ListView 工作。然而,没有运气。我还在这里和那里阅读了一些帖子并尝试匹配,但仍然没有好处。请给我指出哪里出错了。
基本上,我想做的是将逻辑从 VM 拆分到 Helper 类。并且这个类中的逻辑会更新数据但VM不知道。
我的问题是复制文件功能,作业状态不会改变视图数据。我尝试了 Messenger.Default.Send (来自助手)和 Messenger 注册(在 VM 中),以接受更改,但仍然没有运气。
顺便说一句,我正在使用 MVVM Light、WPF、C#。
这是我的模型代码。
public class MyFile : ViewModelBase
{
public string fullFileName { get; set; }
public string fileName { get; set; }
private string _jobStatus;
public string jobStatus
{
get { return _jobStatus; }
set { Set(ref _jobStatus, value); }
}
}
这是我的 Helper 代码。
class FileHelper
{
public List<MyFile> GetFileName(string dir)
{
List<MyFile> lstFiles = new List<MyFile>();
foreach (var file in (new DirectoryInfo(dir).GetFiles()))
{
if (file.Name.ToLower().Contains("xls") && !file.Name.Contains("~$"))
lstFiles.Add(new MyFile() { fullFileName = file.FullName, fileName = file.Name, jobStatus = "-" });
}
return lstFiles;
}
public bool CopyFiles(string destDir, List<MyFile> lstFiles)
{
try
{
int counter = 0;
foreach (MyFile f in lstFiles)
{
f.jobStatus = "Copying";
File.Copy(f.fullFileName, Path.Combine(destDir, f.fileName),true);
f.jobStatus = "Finished";
counter += 1;
Console.WriteLine("M: " + DateTime.Now.ToString("hh:mm:ss") + " " + counter);
Messenger.Default.Send(counter, "MODEL");
}
return true;
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
return false;
}
}
}
这是我的VM代码。
public class MainViewModel : ViewModelBase
{
public ICommand CmdJob { get; private set; }
private ObservableCollection<MyFile> fileList;
public ObservableCollection<MyFile> FileList
{
get { return fileList; }
set { Set(ref fileList, value); }
}
private string counter;
public string Counter
{
get { return counter; }
set { Set(ref counter, value); }
}
public MainViewModel()
{
Messenger.Default.Register<int>(this, "MODEL", UpdateCounter);
CmdJob = new RelayCommand<object>(Action_Job);
Counter = "0";
}
private void UpdateCounter(int bgCounter)
{
Counter = bgCounter.ToString();
RaisePropertyChanged("FileList");
Console.WriteLine("VM: " + DateTime.Now.ToString("hh:mm:ss") + " " + Counter);
}
private void Action_Job(object tag)
{
if (tag == null || string.IsNullOrEmpty(tag.ToString()))
return;
switch (tag.ToString())
{
case "GET": GetFile(); break;
case "COPY": CopyFile(); break;
}
}
private void GetFile()
{
Counter = "0";
List<MyFile> myFs = new FileHelper().GetFileName(@"C:\Test\Original\");
FileList = new ObservableCollection<MyFile>(myFs);
}
private void CopyFile()
{
if (new FileHelper().CopyFiles(@"C:\Test\Destination\", fileList.ToList()))
Messenger.Default.Send("Files copying finished", "VM");
else
Messenger.Default.Send("Files copying failed", "VM");
}
}
这是我的 XAML。
<ListView Grid.Row="0" Grid.Column="0" ItemsSource="{Binding FileList}" Margin="5,5,0,5" HorizontalAlignment="Left" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListView.View>
<GridView>
<GridViewColumn Header="File Name" Width="170" DisplayMemberBinding="{Binding fileName}" />
<GridViewColumn Header="Status" Width="170" DisplayMemberBinding="{Binding jobStatus}" >
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Vertical">
<Button Content="Get file list" Tag="GET" Command="{Binding CmdJob}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Width="80" Height="25" Margin="0,50,0,50"/>
<Button Content="Copy file" Tag="COPY" Command="{Binding CmdJob}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Width="80" Height="25" />
<Label Content="{Binding Counter}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Height="25" FontWeight="Bold" Foreground="Red" Margin="0,50,0,0"/>
</StackPanel>
我阅读了一些帖子,上面写着“更改”,ObservableCollection 不会反映对 View 的更改。所以,我遵循那些帖子解决方案(在模型类中使用通知更改),不适合我。
对我来说,我的个人文件很大,所以我可以看到我的虚拟机上没有更新。
如果您使用小文件大小进行测试,您将看不到差异。
我尝试使用 Messenger 方法,它也没有在 View 上更新,但我的虚拟机可以毫无问题地接受传入的消息。
【问题讨论】:
-
您是否尝试过实现 INotifyPropertyChanged 接口?
-
@mahlatse,我正在使用 MVVM Light,“set { Set(ref xxxx}” 为我完成这项工作。
-
看来我的回答有点不对劲,你试过这个stackoverflow帖子吗? stackoverflow.com/questions/34243936/…
-
那是因为您在 UI 线程中同步设置这些属性。只有最后一个值在 UI 中可见(当 UI 线程有机会更新它时)。考虑使您的视图模型方法
async并执行异步文件复制,可以是awaited。参见例如这里:docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… -
另请注意,如果您只创建新集合实例,而不从现有集合中添加或删除元素,则使用 ObservableCollection 是没有意义的。
标签: c# wpf mvvm mvvm-light observablecollection