【发布时间】:2019-12-16 03:42:40
【问题描述】:
我对 GroupStyle 和 Expander.IsExpanded 绑定有疑问。我的代码基于这个答案:来自@user1 的How to save the IsExpanded state in group headers of a listview。我无法评论这个答案,因为我的声誉不够高,所以这就是我提出这个新话题的原因。
在我的 ListView 我有这个代码:
<!-- Group Container Style -->
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="{Binding Path=Items[0].bIsExpandedGroup}">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold"
Style="{StaticResource DefaultTextBlockItemStyle}"
Text="{Binding Path=Name}"
/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
属性“bIsExpandedGroup”绑定在 DTO_Package 上(对象绑定到 ListView)
public class DTO_Package : ViewModelBase
{
(...)
private bool _bIsExpandedGroup = false;
/// <summary>
/// Used to Expand/Collapse expanders when grouping by Type or Category
///
/// Exception in the OUTPUT :
/// System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'Object') from 'Items' (type 'ReadOnlyObservableCollection`1'). BindingExpression:Path=Items[0].bIsExpandedGroup; DataItem='CollectionViewGroupInternal' (HashCode=15134062); target element is 'Expander' (Name=''); target property is 'IsExpanded' (type 'Boolean') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
/// Parameter name: index'
///
/// </summary>
public bool bIsExpandedGroup
{
get { return _bIsExpandedGroup; }
set
{
_bIsExpandedGroup = value;
OnPropertyChanged(nameof(bIsExpandedGroup));
}
}
(...)
}
此代码有效,但在 OutputWindow 中出现此错误:
System.Windows.Data 错误:17:无法从“项目”(类型“ReadOnlyObservableCollection`1”)获取“项目 []”值(类型“对象”)。 BindingExpression:Path=Items[0].bIsExpandedGroup; DataItem='CollectionViewGroupInternal' (HashCode=29463315);目标元素是'扩展器'(名称='');目标属性是“IsExpanded”(类型“布尔”)ArgumentOutOfRangeException:“System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。 参数名称:index'
感谢您的帮助:)
【问题讨论】: