如果我将我的绑定ListBox
到 ViewModelsObservableCollection
或 XAML 资源CollectionViewSource
,模拟数据会在设计时显示。
有时CollectionViewSource
由于某些 XAML 更改而停止显示此数据,但在重建代码后,它会再次用假数据填充控件。
在我的案例中,分组、排序和过滤是在 ViewModel 中控制的(并从数据库中重试),所以我决定转移到ICollectionView
基于 ViewModel 的属性。不幸的是,视图根本不再获得模拟数据。
这是我的方法的简单示例:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance local:MainWindowViewModel }"
Title="MainWindow" Height="100" Width="525"
>
<Window.Resources>
<CollectionViewSource x:Key="ItemsCollectionViewSource" Source="{Binding ItemsObservableCollection}"/>
</Window.Resources>
<UniformGrid Columns="6">
<ListBox ItemsSource="{Binding ItemsObservableCollection}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding Source={StaticResource ItemsCollectionViewSource}}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsICollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsCollectionView}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsListCollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsBackCollectionViewSource}" Background="LightYellow" />
</UniformGrid>
</Window>
后面的代码:
namespace Test
{
public partial class MainWindow
{
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
}
}
}
和视图模型:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
namespace Test
{
public class MainWindowViewModel
{
public ICollectionView ItemsICollectionView { get; set; }
public CollectionView ItemsCollectionView { get; set; }
public ListCollectionView ItemsListCollectionView { get; set; }
public ObservableCollection<string> ItemsObservableCollection { get; set; }
public CollectionViewSource ItemsBackCollectionViewSource { get; set; }
public MainWindowViewModel()
{
ItemsObservableCollection = new ObservableCollection<string> {"a", "b", "c"};
ItemsICollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection);
ItemsCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as CollectionView;
ItemsListCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as ListCollectionView;
ItemsBackCollectionViewSource = new CollectionViewSource {Source = ItemsObservableCollection};
}
}
}
为了将 CollectionViewSource 移动到 ViewModel 我尝试过的所有方法都不允许我查看模拟数据:
我对这些控件进行了一些调试比较,但它们在运行时的设置几乎相同。我不知道在设计时进行调试的能力。
有什么我想念的,还是必须这样?谢谢