当前位置: 首页 > 编程语言 > C#

如何在列表视图的组头中保存IsExpanded状态share

时间:2023-04-10 23:52:20 C#

如何在列表视图的组头中保存IsExpanded状态ItemsSource设置为CollectionViewSource,包括PropertyGroupDescription以对ListView元素进行分组。CollectionViewSource如下所示:在ListView中,我使用如下自定义组标头:如您所见,Expander的IsExpanded属性设置为true。这意味着每当ListView刷新时,所有Expander控件都会展开。但是我想保存每个Expander的最后状态。我想不出一种方法来为每个ObjectType保留一个Expander状态列表。我正在尝试使用绑定的HashTable和Converter,但我没有提供ObjectType作为ConverterParameter,因为它总是作为字符串传递。但这可能不是解决方案。有人可以给我一个解决方案的提示或想法吗??您可以使用Dictionary创建一个新类(例如ObjectType作为bool值的键)并给它一个索引器:DictionaryexpandStates=newDictionary();publicboolthis[ObjectTypekey]{get{if(!expandStates.ContainsKey(key))returnfalse;返回expandStates[key];}set{expandStates[key]=value;然后,在某个地方的ResourceDictionary中实例化它并像这样将IsExpanded绑定到它:这可能会做得很好:让WPF调用代码并在需要时传递参数的好方法。(WPF允许您将子表达式放在绑定路径中的索引器中,这对我来说是个新闻-虽然不是很好!)如评论中所述,接受的答案是错误的。我写了下面行为,发现了所需要的功能:默认(对象)));privatestaticreadonlyDependencyPropertyExpandedStateStoreProperty=DependencyProperty.RegisterAttached("ExpandedStateStore",typeof(IDictionary),typeof(PersistGroupExpandedStateBehavior),newPropertyMetadata(default(IDictionary)));#endregion#region公共属性publicobjectGroupName{get{return(object)this.GetValue(GroupNameProperty);}set{this.SetValue(GroupNameProperty,value);}}#endregion#region方法受保护覆盖??voidOnAttached(){base.OnAttached();布尔?expanded=this.GetExpandedState();if(expanded!=null){this.AssociatedObject.IsExpanded=expanded.Value;}this.AssociatedObject.Expanded+=这个.OnExpanded;this.AssociatedObject.Collapsed+=this.OnCollapsed;}protectedoverridevoidOnDetaching(){this.AssociatedObject.Expanded-=this.OnExpanded;this.AssociatedObject.Collapsed-=this.OnCollapsed;base.OnDetaching();}privateItemsControlFindItemsControl(){DependencyObjectcurrent=this.AssociatedObject;while(current!=null&&!(currentisItemsControl)){current=VisualTreeHelper.GetParent(current);}if(current==null){返回null;}返回当前作为ItemsControl;私人布尔?GetExpandedState(){vardict=this.GetExpandedStateStore();如果(!dict.ContainsKey(this.GroupName)){返回null;}returndict[this.GroupName];}privateIDictionaryGetExpandedStateStore(){ItemsControlitemsControl=this.FindItemsControl();if(itemsControl==null){thrownewException("行为需要附加到包含在ItemsControl中的扩展器");}vardict=(IDictionary)itemsControl.GetValue(ExpandedStateStoreProperty);if(dict==null){dict=newDictionary();itemsControl.SetValue(ExpandedStateStoreProperty,dict);}返回字典;}privatevoidOnCollapsed(objectsender,RoutedEventArgse){this.SetExpanded(false);}privatevoidOnExpanded(objectsender,RoutedEventArgse){this.SetExpanded(true);}privatevoidSetExpanded(boolexpanded){vardict=this.GetExpandedStateStore();dict[this.GroupName]=扩展;}#endregion}它将一个字典附加到包含ItemsControl的字典中,该ItemsControl保存每个组项目的展开状态。即使控件中的项目发生变化,这也会保持不变。用法:...标记的答案在.Net4.5中不起作用。一个简单的解决方案是添加一个privatebool_isExpanded=true;publicboolIsExpanded{get{return_isExpanded;}设置{_isExpanded=值;ViewModel的属性(在这种情况下,无论CurrentListViewData持有什么),然后执行:在您的模板上。像WPF一样简单有效以上就是C#学习教程:如何将IsExpanded状态共享的所有内容保存在列表视图的组头中。如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——本文来自网络收藏,不代表立场,如涉及侵权,请点击右转联系管理员删除。如需转载请注明出处: