【发布时间】:2014-02-28 14:04:35
【问题描述】:
您好,我以 MVVM 方式编写了小程序来测试 CollectionViewSource 的使用情况。我有一个包含 ListBox 并具有依赖属性项的 UserControl,它将绑定项从该控件“转发”到 ListBox ItemsSource:
<UserControl x:Class="TestingCollectionViewSource.TestControlWithListBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:TestingCollectionViewSource="clr-namespace:TestingCollectionViewSource"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ListBox ItemsSource="{Binding Items,
RelativeSource={RelativeSource AncestorType=TestingCollectionViewSource:TestControlWithListBox}}" />
</Grid>
</UserControl>
public partial class TestControlWithListBox : UserControl
{
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof (IEnumerable<string>), typeof (TestControlWithListBox), new PropertyMetadata(default(IEnumerable<string>)));
public IEnumerable<string> Items
{
get { return (IEnumerable<string>) GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public TestControlWithListBox()
{
InitializeComponent();
}
}
我尝试使用 ObservableCollection 和 CollectionViewSource 视图绑定到项目。 它适用于 ObservableCollection,但不适用于 CollectionViewSource。
<Window x:Class="TestingCollectionViewSource.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:TestingCollectionViewSource="clr-namespace:TestingCollectionViewSource" Width="500" Height="500">
<Grid>
<TestingCollectionViewSource:TestControlWithListBox Items="{Binding Path=ItemsCollectionViewSource.View}"/>
</Grid>
</Window>
public class MainWindowViewModel : Screen
{
private ObservableCollection<string> items;
public ObservableCollection<string> Items
{
get { return items; }
set
{
items = value;
NotifyOfPropertyChange(() => Items);
}
}
private CollectionViewSource itemsCollectionViewSource;
public CollectionViewSource ItemsCollectionViewSource
{
get { return itemsCollectionViewSource; }
set
{
itemsCollectionViewSource = value;
NotifyOfPropertyChange(() => ItemsCollectionViewSource);
}
}
public MainWindowViewModel()
{
DisplayName = "Testing testing testing";
Items = new ObservableCollection<string>()
{
"1",
"2 2",
"3 3 3",
"4 4 4 4"
};
ItemsCollectionViewSource = new CollectionViewSource() { Source = Items};
}
}
但是,如果我尝试将 CollectionViewSource.View 绑定到 ListBox 没有问题,并且所有列表项都包含在 ListBox 中,如下图所示:
这种行为的原因可能是什么,有什么解决办法吗?
【问题讨论】:
标签: wpf wpf-controls