为什么这么难以做到,严重:P我有以下几点:
public BindingList<Dialogue> Dialogues { get; set; }
public CollectionView DialoguesCollectionView { get; set; }
在这个ViewModel的构造函数中,我做了:
SubDialogues = new BindingList<SubDialogue>();
SubDialogues.ListChanged += (sender, args) =>
{
OnPropertyChanged(nameof(SubDialogues));
//HACK: Temporary solution...
if (args.ListChangedType == ListChangedType.ItemAdded ||
args.ListChangedType == ListChangedType.ItemDeleted)
{
SubDialoguesCollectionView.Refresh();
}
};
SubDialoguesCollectionView = new ListCollectionView(SubDialogues);
SubDialoguesCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
每当我修改绑定列表中的项目时,它立即被反映出来。但是,这不会计入添加或删除项目,因此我强制刷新。
但是,我还想在Name
属性更改时刷新列表,因此会相应地重新排序,这就是我的问题开始的地方。
我的视图中的TreeView使用SubDialoguesCollectionView
作为其ItemSource
之一的HierarchicalDataTemplate
。每当我在TreeView中选择一个项目并且底层的CollectionView因任何原因而被刷新时,它就会丢失选择,而是跳转到整个列表的父级。
我不希望这种情况发生,我想保留项目的选择,即使它的偏移由于重新排序而改变了。任何人都可以帮我弄清楚如何让我的工作方式如何?我已经尝试了一切:SortableBindingList,Behaviors,移动项而不是刷新,列表继续。我开始长出白发! :P
如果有其他方法我可能会忽略,我也很想听听它们。我想要的最后一个列表是当任何绑定对象的Name
属性发生更改时重新排序,但不会丢失TreeView中该对象的选择。
根据要求设置我的代码库设置的复制/粘贴版本(albit简化和展平):https://gist.github.com/LennardF1989/59a42c7be474061f14bd
我遗漏了上述失败的尝试,这是我尝试任何事情之前的状态。
答案 0 :(得分:3)
这里实际上有几个问题在起作用。说实话,主要的问题是你没有正确使用数据绑定,如果你使用像MVVM这样的东西,那么你将操纵视图模型,UI就会陷入困境。实际上,视图元素内部会发生一些复杂的交互。
在进一步讨论之前,我只是指出我对您的代码所做的一些更改。
Refresh()
成员更新排序。现在,发生的事情是TreeView维护一个TreeViewItem的内部列表,每个TreeViewItem都有一个IsSelected
标志(在MVVM应用程序中,您可以将它们绑定到相应视图模型中的属性) )。刷新排序列表时,TreeView通过从头开始为相关子树重新创建TreeViewItem来响应。当前选择的TreeViewItem与TreeView分离,因此框架通过选择父节点而不是Quest来响应。通常,您可以调用treeview.ItemContainerGenerator.ContainerFromItem(item)
从项中获取新的TreeView,但由于在运行时创建节点的动态方式,这不能与HierarchicalDataTemplates一起使用。诀窍是手动遍历TreeView的层次结构,寻找具有所选值的节点。
这是新代码:
public interface INameable
{
string Name { get; set; }
}
public class Quest : ViewModelBase, INameable
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged();
}
}
private ObservableCollection<Dialogue> _Dialogues;
public ObservableCollection<Dialogue> Dialogues
{
get { return this._Dialogues; }
set { this._Dialogues = value; RaisePropertyChanged(); }
}
private ICollectionView _SortedDialogues;
public ICollectionView SortedDialogues
{
get { return this._SortedDialogues; }
set { this._SortedDialogues = value; RaisePropertyChanged(); }
}
// this is actually a bit messy, I'll leave it to you to find a cleaner way of doing this
public Func<object> GetSelected;
public Action<object> SetSelected;
public Quest()
{
Dialogues = new ObservableCollection<Dialogue>();
this.SortedDialogues = CollectionViewSource.GetDefaultView(Dialogues);
this.SortedDialogues.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
}
public void AddDialogue(Dialogue dlg)
{
this.Dialogues.Add(dlg);
dlg.PropertyChanged += Dlg_PropertyChanged;
SortDialogues();
}
private void Dlg_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
SortDialogues();
}
private void SortDialogues()
{
var selected = GetSelected(); // get currently selected item
this.SortedDialogues.Refresh(); // bam! treeviewitmes get destroyed.
SetSelected(selected); // so reselect it immediately
}
}
public class Dialogue : ViewModelBase, INameable
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged();
}
}
}
public partial class MainWindow : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private object _selectedObject = new object();
public object SelectedObject
{
get
{
return _selectedObject;
}
set
{
_selectedObject = value;
OnPropertyChanged();
}
}
public ObservableCollection<Quest> Quests
{
get { return _quests; }
set
{
_quests = value;
OnPropertyChanged();
}
}
private ObservableCollection<Quest> _quests;
public MainWindow()
{
Quests = new ObservableCollection<Quest>();
InitializeComponent();
}
private void AddQuest(object sender, RoutedEventArgs e)
{
Quests.Add(new Quest
{
Name = "Quest",
GetSelected = () => this.SelectedObject,
SetSelected = (selected) => {
ItemContainerGenerator gen = _treeView.ItemContainerGenerator;
TreeViewItem item = ContainerFromItem(gen, selected);
if (item != null)
item.IsSelected = true;
}
,
});
}
private void AddDialogue(object sender, RoutedEventArgs e)
{
if (_treeView.SelectedItem is Quest)
{
var dlg = new Dialogue
{
Name = "Dialogue"
};
(_treeView.SelectedItem as Quest).AddDialogue(dlg);
}
}
// courtesy http://stackoverflow.com/questions/24859511/get-treeviewitem-for-treeview-logical-element
private static TreeViewItem ContainerFromItem(ItemContainerGenerator containerGenerator, object item)
{
TreeViewItem container = (TreeViewItem)containerGenerator.ContainerFromItem(item);
if (container != null)
return container;
foreach (object childItem in containerGenerator.Items)
{
TreeViewItem parent = containerGenerator.ContainerFromItem(childItem) as TreeViewItem;
if (parent == null)
continue;
container = parent.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (container != null)
return container;
container = ContainerFromItem(parent.ItemContainerGenerator, item);
if (container != null)
return container;
}
return null;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这里是TreeView的XAML:
<TreeView x:Name="_treeView" behaviors:TreeViewHelper.SelectedItem="{Binding Path=SelectedObject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TreeViewItem IsExpanded="True">
<TreeViewItem.Header>
<TextBlock Text="Project" Margin="5,0,0,0" />
</TreeViewItem.Header>
<TreeViewItem ItemsSource="{Binding Quests}" IsExpanded="True">
<TreeViewItem.Header>
<TextBlock Text="Quests" Margin="5,0,0,0" />
</TreeViewItem.Header>
<TreeViewItem.Resources>
<HierarchicalDataTemplate DataType="{x:Type testApplication:Quest}" ItemsSource="{Binding SortedDialogues, UpdateSourceTrigger=PropertyChanged}">
<TextBlock Text="{Binding Name}" Margin="5,0,0,0" />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type testApplication:Dialogue}">
<TextBlock Text="{Binding Name}" Margin="5,0,0,0" />
</DataTemplate>
</TreeViewItem.Resources>
</TreeViewItem>
</TreeViewItem>
</TreeView>
最后是绑定当前所选项目的行为,它以各种形式存在于网络周围,所以我不知道它最初来自哪里:
public class TreeViewHelper
{
private static Dictionary<DependencyObject, TreeViewSelectedItemBehavior> behaviors = new Dictionary<DependencyObject, TreeViewSelectedItemBehavior>();
public static object GetSelectedItem(DependencyObject obj)
{
return (object)obj.GetValue(SelectedItemProperty);
}
public static void SetSelectedItem(DependencyObject obj, object value)
{
obj.SetValue(SelectedItemProperty, value);
}
// Using a DependencyProperty as the backing store for SelectedItem. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(TreeViewHelper), new UIPropertyMetadata(null, SelectedItemChanged));
private static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (!(obj is TreeView))
return;
if (!behaviors.ContainsKey(obj))
behaviors.Add(obj, new TreeViewSelectedItemBehavior(obj as TreeView));
TreeViewSelectedItemBehavior view = behaviors[obj];
view.ChangeSelectedItem(e.NewValue);
}
private class TreeViewSelectedItemBehavior
{
TreeView view;
public TreeViewSelectedItemBehavior(TreeView view)
{
this.view = view;
view.SelectedItemChanged += (sender, e) => SetSelectedItem(view, e.NewValue);
}
internal void ChangeSelectedItem(object p)
{
TreeViewItem item = (TreeViewItem)view.ItemContainerGenerator.ContainerFromItem(p);
// item will be null for HierarchicalDataTemplates
if (item != null)
item.IsSelected = true;
}
}
}