我的一个视图模型中有一个非常奇怪的行为.
首先,在这个目录中我有三个csv文件.当我首先开始调试它进入foreach然后它进入第一行this.allDatabases.Add(Path.GetFileNameWithoutExtension(item));并且在下一步中发生一些奇怪的行为,它进入视图.我需要获取文件的名称并将它们添加到集合中.在另一个班级这种方法运作良好,但现在只是......我不知道.
有关更多信息,我使用了Visual Studio 2015社区和.NET Framework 4.6
我没有任何例外.FileConstants.PATH_TO_DATABASE是一个目录,我有三个csv文件.为了更好的解释,我将展示两张照片.
第一
调试的下一步是
我的代码:
private ObservableCollection<string> allDatabases;
public IEnumerable<string> AllDatabases
{
get
{
foreach (var file in Directory.GetFiles(DirectoryPath, "*.csv", SearchOption.AllDirectories))
{
this.allDatabases.Add(Path.GetFileNameWithoutExtension(file)); // after first add is go in view and not return back in foreach loop
}
return this.allDatabases;
}
}
Run Code Online (Sandbox Code Playgroud)
和观点
<Window x:Class="Growthanalyzer.App.Views.Dialogs.NewView"
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:Growthanalyzer.App.Views.Dialogs"
xmlns:vms="clr-namespace:Growthanalyzer.App.ViewModels.Dialogs"
mc:Ignorable="d"
Title="New" Height="300" Width="300">
<StackPanel Orientation="Vertical">
<StackPanel.DataContext>
<vms:NewViewModel />
</StackPanel.DataContext>
<ListBox ItemsSource="{Binding AllDatabases}" MinHeight="150" Width="250" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
我真的不知道发生了什么,问题是什么.如果需要更多信息,请问我.
我该如何解决这个错误,以及从哪些方面可以获得这个错误?
好吧,我想我至少看到了一个潜在的问题(绝对是要避免的代码)......
每次评估AllDatabases属性时,都会将所有文件添加到集合中.属性提取不应该这样做 - 它们不应该改变状态.
相反,你应该一次填充集合(例如在构造函数中),然后你的AllDatabases属性应该只返回对集合的引用 - 很可能输入,ObservableCollection<string>因为客户知道它是可观察的是合理的.
我不确定这是否能解决问题,但我可以很容易地理解,每次访问时绑定一个修改集合的属性很容易造成一些非常奇怪的行为.