我很难将ListView
与ObservableCollection
绑定在另一个班级。
我的xaml:
<ListView Height="117" HorizontalAlignment="Left" Margin="20,239,0,0" Name="lvResults" VerticalAlignment="Top" Width="759" ItemsSource="{Binding RuleSearch.FileMatches}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding FileName}"/>
<GridViewColumn Header="Size" Width="120" DisplayMemberBinding="{Binding DirectoryName}"/>
<GridViewColumn Header="Date" Width="120" DisplayMemberBinding="{Binding Size}"/>
<GridViewColumn Header="Full Path" Width="120" />
<GridViewColumn Header="Some Meaningless Data" Width="120" />
</GridView>
</ListView.View>
</ListView>
代码背后的Xaml:
private Search _ruleSearch = new Search();
public Search RuleSearch { get { return _ruleSearch; }}
在搜索课程中:
public ObservableCollection<Result> FileMatches { get; private set; }
请注意,如果这会产生影响,则会对新主题进行更改:
private void FindResultOnNewThreads()
{
FileMatches.Clear();
Parallel.ForEach(_fileList, file =>
{
foreach (Regex search in SearchTermList.Where(search => search.IsMatch(file)))
{
lock (FileMatches)
{
FileInfo fileInfo = new FileInfo(file);
FileMatches.Add(new Result
{
Attributes = fileInfo.Attributes,
DirectoryName = fileInfo.DirectoryName,
Extension = fileInfo.Extension,
FileName = fileInfo.Name,
FullNamePath = fileInfo.FullName,
Size = fileInfo.Length
});
}
}
});
}
结果类:
public class Result
{
public string FileName { get; set; }
public string DirectoryName { get; set; }
public string FullNamePath { get; set; }
public long Size { get; set; }
public string Extension { get; set; }
public FileAttributes Attributes { get; set; }
}
问题确实是,我自己学习wpf并且无法在WPF中找到数据绑定的规则集。我知道它需要属性和公共属性,除了我被困住。
答案 0 :(得分:1)
可能你的listViews DataContext没有设置为UserControls或Windows或其他任何你拥有RuleSearch道具的地方。
您可以在xaml.cs代码隐藏中设置它。
lvResult.DataContext = this;
或在xaml
<ListView Height="117" HorizontalAlignment="Left" Margin="20,239,0,0" Name="lvResults" VerticalAlignment="Top" Width="759" ItemsSource="{Binding Path=RuleSearch.FileMatches, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding FileName}"/>
<GridViewColumn Header="Size" Width="120" DisplayMemberBinding="{Binding DirectoryName}"/>
<GridViewColumn Header="Date" Width="120" DisplayMemberBinding="{Binding Size}"/>
<GridViewColumn Header="Full Path" Width="120" />
<GridViewColumn Header="Some Meaningless Data" Width="120" />
</GridView>
</ListView.View>
</ListView>
其中typeOfAncestor是您的usercontrol / window的类型......
答案 1 :(得分:0)
您的Search
类需要实现INotifyPropertyChanged,用于让用户知道代码隐藏中的属性何时更改(在本例中为FileMatches
)。这将涉及注册FileMatches.CollectionChanged
事件的回调,然后使用属性名称“FileMatches”引发INotifyPropertyChanged.PropertyChanged
事件。
请注意,如果您希望集合中的值与UI保持同步,则还应在Result类上实现INotifyPropertyChanged。 (通过查看代码,Result类的内容看起来是不变的,因此您不需要这样做。)