在我的项目中,我目前有一个 ObservableCollection
填充在我的 ViewModel
构造函数中。此 ObservableCollection
包含一个自定义对象,该对象具有两个属性(均为字符串)。
目前,对应的 XAML/View 包含两个单独的列表框,这两个列表框都绑定(bind)到 DataTemplate
,后者选择将哪个属性显示为 ListBox
中的条目.在本例中,它显示“propertyOne”。
是否有可能有一个 DataTemplate
可以根据“propertyTwo”的内容选择每个 ListBox
项目的去向?
我已经研究了与我的情况类似的示例,这些示例使用了 CollectionViewSource
但我不太确定如何将其实现到我的项目中,因为我对使用 WPF 和以下内容还很陌生MVVM结构。这是否涉及在 View 的代码隐藏中创建过滤器事件?
下面列出了我认为有助于理解我的问题的代码片段。任何解决此问题的帮助将不胜感激。
查看
<Window.Resources>
<DataTemplate x:Key="ListBoxTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=propertyOne}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox x:Name="ListBoxOne"
Height="Auto"
Width="Auto"
ItemsSource="{Binding TestCollection}"
ItemTemplate="{StaticResource ListBoxTemplate}" />
<ListBox x:Name="ListBoxTwo"
Height="Auto"
Width="Auto"
ItemsSource="{Binding TestCollection}"
ItemTemplate="{StaticResource ListBoxTemplate}" />
View 模型
public class ViewModel
{
public ObservableCollection<Item> TestCollection { get; set; }
public ViewModel()
{
//populates the collection from an XML file
//with propertyOne & propertyTwo for each item
TestCollection = CustomObjectClass.DeserializeToColl<Item>("path");
}
}
自定义对象类
public class CustomObjectClass
{
public string propertyOne { get; set; }
public string propertyTwo { get; set; }
}
最佳答案
<DataTemplate x:Key="ListBoxTemplate">
<StackPanel>
<StackPanel.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=propertyTwo}" Value="read">
<Setter Property="StackPanel.Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<TextBlock Text="{Binding Path=propertyOne}" />
</StackPanel>
</DataTemplate>
关于c# - 将 ObservableCollection 过滤到多个列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191417/