对于我的 WPF 应用程序,我需要 CollectionViewSource 来在集合中启用选择、筛选、排序和分组。但 CollectionViewSource 不是像 IList 那样的类型安全集合,例如属性 View.CurrentItem 是一个对象。如果我们使用它们,我们需要铸造它们。
是否有任何支持 Generic 的 CollectionViewSource 替代方案?或者也许有人知道 CollectionViewSource 不是泛型的原因?
=============================
我基于标准 CollectionViewSource 制作了一个通用 CollectionViewSource。对于它是否是在 XAML 之外实例化的集合类的更好替代方案,有什么评论吗?或者还有其他更好的选择?
编辑1:添加通用CollectionViewSource
namespace Data
{
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
public class CollectionViewSource<T> : CollectionViewSource
{
public T CurrentItem => this.View != null ? (T)this.View.CurrentItem : default(T);
public new IEnumerable<T> Source
{
get
{
return (IEnumerable<T>)base.Source;
}
set
{
base.Source = value;
}
}
public IEnumerable<T> ViewItems => this.View != null ? Enumerable.Cast<T>(this.View) : (IEnumerable<T>)null; …
Run Code Online (Sandbox Code Playgroud) 标准事件处理程序(带有运算符+=
)是内存泄漏的原因之一(如果它没有被取消注册/处置(带有-=
运算符))。
微软用WeakEventManager
它的继承方式解决了这个问题:PropertyChangedEventManager, CollectionChangedEventManager, CurrentChangedEventManager, ErrorsChangedEventManager
等等。
内存泄漏的简单示例代码是:
public class EventCaller
{
public static event EventHandler MyEvent;
public static void Call()
{
var handler = MyEvent;
if (handler != null)
{
handler(null, EventArgs.Empty);
Debug.WriteLine("=============");
}
}
}
public class A
{
string myText;
public A(string text)
{
myText = text;
EventCaller.MyEvent += OnCall;
// Use code below and comment out code above to avoid memory leakage.
// System.Windows.WeakEventManager<EventCaller, EventArgs>.AddHandler(null, "MyEvent", OnCall);
} …
Run Code Online (Sandbox Code Playgroud) 我创建按钮作为ListBox项目.使用键盘快捷键,所选项目/按钮将更改为第一个字符与按下的键相同的按钮.问题是焦点项(虚线矩形)不会与所选项同步.如果我们使用键盘箭头,则不存在此问题.短代码是:
<ListBox x:Name="ListBoxRef"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
DataContext="{Binding Path=ListViewSource}" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" IsTabStop="False"
Command="{Binding ElementName=UserControlTypeSelectionView, Path=DataContext.SelectCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}">
<Button.Template>
<ControlTemplate>
<TextBlock Text="{Binding Path=Name}" />
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
在如何以焦点方式将焦点设置为已具有焦点的WPF ListBox中的SelectedItem?,解决方案是使用Focus方法和C#方面.
是否可以在MVVM中仅使用XAML?