我有一个绑定到ListBox的类:
class FolderFM : INotifyPropertyChanged
{
public FolderFM(string path)
{
this.Folder = new DirectoryInfo(path);
this.Name = Folder.Name;
}
private string name;
private DirectoryInfo folder;
private ObservableCollection<FileInfo> matchingFiles;
...
public ObservableCollection<FileInfo> MatchingFiles
{
get { return matchingFiles; }
set
{
matchingFiles = value;
FireWhenPropertyChanged("MatchingFiles");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void FireWhenPropertyChanged(string property)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(property, new PropertyChangedEventArgs(property));
}
}
}
XAML代码:<ListBox Name="lstFolders" ItemsSource="{Binding}" Style="{StaticResource FolderBoxStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="25" />
</Grid.ColumnDefinitions>
<Label Content="{Binding Path=Name}" FontWeight="Bold" FontSize="13" />
<Button Content="{Binding Path=MatchingFiles, Converter={StaticResource lcc}}" Grid.Column="1" FontWeight="Bold" Foreground="Red" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
发生更新的代码后面:
private void btnAnalyze_Click(object sender, RoutedEventArgs e)
{
List<FileInfo> remainingFiles = files;
foreach (FolderFM currentFolder in folders)
{
currentFolder.MatchingFiles = new ObservableCollection<FileInfo>();
string folderName = currentFolder.Folder.Name;
string[] splitName = folderName.Split(' ');
for (int i = 0; i < remainingFiles.Count; i++)
{
if (remainingFiles[i] == null)
continue;
FileInfo fileName = remainingFiles[i];
string searchedName = fileName.Name;
matchScore = 0;
int searchCount = 0;
foreach (string part in splitName)
{
if (part.Length < 3 || part == "the")
continue;
matchScore += searchedName.Contains(part) ? 1 : 0;
searchCount += 1;
}
if (matchScore == searchCount)
{
string destination = System.IO.Path.Combine(currentFolder.Folder.FullName, fileName.Name);
if (File.Exists(destination))
continue;
Directory.Move(fileName.FullName, destination);
currentFolder.MatchingFiles.Add(remainingFiles[i]);
//lstFolders.Items.Refresh();
remainingFiles[i] = null;
}
}
}
populateFiles();
}
附加的Converter接受ObservableCollection并返回它的Count作为字符串。
应用程序正在正常工作,值正在更新,但更改没有反映在UI上。
然而,当我调用:lstFolders.Items.Refresh ();UI得到更新。
我错过/做错了什么??
我看了一些问题,比如:与INotifyPropertyChanged绑定的WPF不更新但我一直没能解决这个问题。
编辑:DataContext正在被这个方法分配:
private void populateFolders()
{
folders = getFolders(selectedFolder.FullName);
lstFolders.ItemsSource = folders;
}
private List<FolderFM> getFolders(string path)
{
List<FolderFM> d = new List<FolderFM>();
foreach (string folder in Directory.GetDirectories(path))
{
d.Add(new FolderFM(folder));
}
return d;
}
将我的评论转换成答案:
尝试直接绑定到MatchingFiles.Count.
与其创建新的ObservableCollection
,不如将其替换为.Clear()
。