下面是一个最小的例子,我不可能减少它。
我在ViewModel中创建一个实时过滤的CollectionView,如下所示:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
namespace AntiBonto.ViewModel
{
[Serializable]
public class Person
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public string Name { get; set; }
public override string ToString()
{
return Name;
}
private int num;
public int Num
{
get { return num; }
set { num = value; RaisePropertyChanged(); }
}
}
class ObservableCollection2<T> : ObservableCollection<T>
{
public ObservableCollection2() : base() { }
public ObservableCollection2(T[] t) : base(t) { }
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection)
{
Items.Add(i);
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
class MainWindow: ViewModelBase
{
public MainWindow() { }
private ObservableCollection2<Person> people = new ObservableCollection2<Person>();
public ObservableCollection2<Person> People
{
get
{
return people;
}
set
{
people = value;
RaisePropertyChanged();
}
}
public ICollectionView Team
{
get
{
CollectionViewSource cvs = new CollectionViewSource { Source = People, IsLiveFilteringRequested = true, LiveFilteringProperties = { "Num" } };
cvs.View.Filter = p => ((Person)p).Num != 11;
return cvs.View;
}
}
public ICollectionView Ujoncok
{
get
{
CollectionViewSource cvs = new CollectionViewSource { Source = People, IsLiveFilteringRequested = true, LiveFilteringProperties = { "Num" } };
cvs.View.Filter = p => ((Person)p).Num == 11;
return cvs.View;
}
}
}
}
GUI有一个按钮,用于修改People集合中的Person对象:
<Window x:Class="AntiBonto.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:vm="clr-namespace:AntiBonto.ViewModel"
mc:Ignorable="d"
Title="AntiBonto" Width="1024" Height="768">
<Window.DataContext>
<vm:MainWindow/>
</Window.DataContext>
<Window.Resources>
<FrameworkElement x:Key="DataContextProxy" DataContext="{Binding}"/> <!-- workaround, see http://stackoverflow.com/questions/7660967 -->
</Window.Resources>
<TabControl>
<TabItem Header="Tab2">
<StackPanel>
<Button Content="Does" Click="Button_Click"/>
<ContentControl Visibility="Collapsed" Content="{StaticResource DataContextProxy}"/>
<!-- workaround part 2 -->
<DataGrid ItemsSource="{Binding Ujoncok}" CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Who" ItemsSource="{Binding DataContext.Team, Source={StaticResource DataContextProxy}, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</TabItem>
</TabControl>
</Window>
我从这样的XML文件中加载数据:
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Xml.Serialization;
namespace AntiBonto
{
[Serializable]
public class AppData
{
public Person[] Persons;
}
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private string filepath = "state.xml";
private AppData AppData
{
get { return new AppData { Persons = viewModel.People.ToArray()}; }
set { viewModel.People.AddRange(value.Persons);}
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var xs = new XmlSerializer(typeof(AppData));
if (File.Exists(filepath))
{
using (var file = new StreamReader(filepath))
{
AppData = (AppData)xs.Deserialize(file);
}
}
}
private ViewModel.MainWindow viewModel { get { return (ViewModel.MainWindow)DataContext; } }
private void Button_Click(object sender, RoutedEventArgs e)
{
Person p = viewModel.People.First(q => q.Name == "Ferencz Katalin");
if (p.Num == 11)
p.Num = 0;
else
p.Num= 11;
}
}
}
,XML文件是这样的:
<?xml version="1.0" encoding="utf-8"?>
<AppData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Persons>
<Person>
<Name>Person1</Name>
<Num>0</Num>
</Person>
<Person>
<Name>Person2</Name>
<Num>0</Num>
</Person>
</Persons>
</AppData>
当我单击按钮一次或两次时,我会收到NullReference
个异常。没有内在的例外。我的代码中没有出现异常,但在框架代码中,因此它不显示源代码,我无法找出哪个对象为null以及异常来自何处。我没有设法“进入.NET源代码”,它仍然告诉我没有可用的源。
这是一个堆栈跟踪:
在System.Windows.Data.ListCollectionView.RestoreLiveShaping()处 System.Windows.Threading.ExceptionWrapper.InternalRealCall(代表 回调,对象args,Int32 numArgs)at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, 委托回调,Object args,Int32 numArgs,Delegate catchHandler) 在System.Windows.Threading.DispatcherOperation.InvokeImpl()at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(对象 国家) System.Threading.ExecutionContext.RunInternal(执行上下文 executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态)at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext,ContextCallback回调,对象状态)at System.Windows.Threading.DispatcherOperation.Invoke()at System.Windows.Threading.Dispatcher.ProcessQueue()at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&amp;处理) MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam, IntPtr lParam,Boolean&amp;处理) MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)at System.Windows.Threading.ExceptionWrapper.InternalRealCall(代表 回调,对象args,Int32 numArgs)at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, 委托回调,Object args,Int32 numArgs,Delegate catchHandler) 在 System.Windows.Threading.Dispatcher.LegacyInvokeImpl(的DispatcherPriority 优先级,TimeSpan超时,委托方法,对象args,Int32 在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32)的numArgs) msg,IntPtr wParam,IntPtr lParam)at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)at at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame 框架) System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架) 在System.Windows.Application.RunDispatcher(Object ignore)at System.Windows.Application.RunInternal(窗口窗口)at System.Windows.Application.Run(窗口窗口)at System.Windows.Application.Run()在AntiBonto.App.Main()中 D:\ Marci \Programozás\ AntiBonto \ AntiBonto \ obj \ Debug \ App.g.cs:第0行at System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)在System.AppDomain.ExecuteAssembly(String assemblyFile, 证据assemblySecurity,String [] args)at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()at System.Threading.ThreadHelper.ThreadStart_Context(Object state)at System.Threading.ExecutionContext.RunInternal(执行上下文 executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态)at System.Threading.ThreadHelper.ThreadStart()
答案 0 :(得分:3)
我不知道为什么,但这解决了这个错误:
public ICollectionView Team
{
get
{
CollectionViewSource cvs = new CollectionViewSource { Source = People, IsLiveFilteringRequested = true, LiveFilteringProperties = { "Num" } };
cvs.View.Filter = p => ((Person)p).Num != 11;
cvs.View.CollectionChanged += EmptyEventHandler;
return cvs.View;
}
}
private void EmptyEventHandler(object sender, NotifyCollectionChangedEventArgs e) { }
我试图调试异常发生的地方,我想在集合发生变化时设置断点。订阅活动使得例外情况消失了。
答案 1 :(得分:0)
我花了很长时间尝试调试System.Windows并且无处可去,欢迎您尝试。
对于至少有效的创可贴解决方法,from my question我发现expireAfterSeconds
会导致问题,而new CollectionViewSource
却没有。
你提到这有两个问题:
1)我一直在修改基本集合,需要刷新我的过滤器
您可以使用ObservableCollections并监听版本,然后更新已过滤的实例来解决此问题。
因此,对于每个新的时间,您需要一个CollectionViewSource,创建一个新的ObservableCollection,并跟踪它,向原始的ObservableCollection添加一个监听器,并将更新推送到CollectionViewSource的版本。
优雅?号功能?是。
2)我使用了GetDefaultView无法使用的实时整形。
使用GetDefaultView始终可以使用它,您能显示创建视图的位置吗?
我注意到的一个相似之处是我使用了ObservableCollection的扩展。如果你只使用标准的ObservableCollection,你有问题吗?