【发布时间】:2015-01-28 11:43:39
【问题描述】:
在我的项目中,我目前有一个 ObservableCollection 填充在我的 ViewModel 构造函数中。这个ObservableCollection 包含一个自定义对象,它有两个属性(两个字符串)。
目前,XAML/View 对应项包含两个单独的列表框,这两个列表框都绑定到 DataTemplate,该 DataTemplate 选择要显示为 ListBox 中的条目的属性。在这种情况下,它显示“propertyOne”。
是否有可能有一个DataTemplate 可以根据“propertyTwo”的内容选择每个ListBox-item 的去向?
我研究了与我的情况类似的示例,它使用了CollectionViewSource,但我不太确定如何在我的项目中实现它,因为我对使用 WPF 和遵循 MVVM 结构还很陌生。这是否涉及在 View 的代码隐藏中创建过滤器事件?
下面列出的是我认为有助于理解我的问题的代码的 sn-ps。任何有关解决此问题的帮助将不胜感激。
查看
<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}" />
视图模型
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; }
}
【问题讨论】:
-
确定我明白了你的问题 - 你想让第二个
ListBox显示 propertyTwo? -
认为您需要重新表述问题。甚至可能添加一个具有所需输出的示例。
-
没有。列表框仍将显示 propertyOne,但由 propertyTwo 决定它转到哪个“ListBox”。例如如果自定义对象将字符串“read”设置为“propertyTwo”,则该对象(其 propertyOne 显示在“ListBox”中)将发送到“ListBoxTwo”。
-
在纯 xaml 中我唯一能想到的是将可见性设置为使用 datatrigger 的样式折叠...因此您将所有内容添加到 2 个列表框,但容器只是折叠了。除了你需要在后面做一些代码
-
1.
CustomObjectClass是可变的(即 setter 是公共的,并且类实现了INotifyPropertyChanged接口)? 2. 使用哪个版本的WPF?
标签: c# wpf mvvm observablecollection collectionviewsource