你能告诉我为什么这段代码不起作用吗?
我有一个带有可观察的搜索结果集合的视图模型,它具有可观察的结果属性集合。我似乎无法像我想要的那样显示结果属性的嵌套集合。
以下是对象(为便于阅读而抽象):
class ViewModel
{
public ObservableCollection<SearchResults<TDomain>> SearchResults { get; set; }
}
class SearchResults<TDomain>
{
public TDomain Result { get; set; }
public ObservableCollection<ResultProperty> ResultProperties { get; set; }
}
class ResultProperty
{
public string PropertyValue { get; set; }
}
这是我无法开始工作的 xaml。DataContext 设置为 ViewModel:
<StackPanel>
<ItemsControl ItemsSource={Binding SearchResults}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text={Binding Result.Id}/>
<StackPanel Orientation="Horizontal">
<ItemsControl ItemsSource={Binding ResultProperties}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding PropertyValue}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Text="PLACEHOLDER /////"/>
</StackPanel>
我正在寻找的结果是这样的:
[Stack panel to keep things orderly]
1
property1property2property3...
2
property1property2property3...
3
property1property2property3...
PLACEHOLDER /////
我得到的结果是这些
[Stack panel to keep things orderly]
1
2
3
PLACEHOLDER /////
换句话说,绑定没有拾取字符串。我已经验证了这些集合的填充量与预期的一样。但我无法让 xaml 工作。
* *附加信息
好的,所以我尝试了一些解决方案,但它们不起作用,所以我将添加更多详细信息,因为我可能遗漏了有关集合如何更新的一些信息。
视图模型上有一个名为“搜索”的按钮,它使用一个 ICommand 调用视图模型的 TrySearch 方法,如下所示:
public void TrySearch()
{
var results = _model.GetAll();
foreach(var result in results)
this.SearchResults.Add(new SearchResults<TDomain>(result));
}
由于集合的更新方式,这是否有原因?SearchResults 是一个依赖属性(我知道我知道,它应该是 INPC,但它不是,它的依赖项),但其他集合不是。这会是个问题吗?