C# 无法通过样式为列表框设置GroupStyle?

C# 无法通过样式为列表框设置GroupStyle?,c#,.net,wpf,C#,.net,Wpf,我正在尝试创建一种样式,该样式将为我的ListBox控件设置GroupStyle属性,但我遇到编译时错误: The Property Setter 'GroupStyle' cannot be set because it does not have an accessible set accessor. 我的样式设置器如下所示: <Setter Property="ListBox.GroupStyle"> <Setter.Value

我正在尝试创建一种样式,该样式将为我的ListBox控件设置GroupStyle属性,但我遇到编译时错误:

The Property Setter 'GroupStyle' cannot be set because it does not have an accessible set accessor. 
我的样式设置器如下所示:

        <Setter Property="ListBox.GroupStyle">
            <Setter.Value>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Name}" />
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </Setter.Value>
        </Setter>

是否有解决方法,而且,如果这个属性没有setter,那么我们首先如何在XAML中为它使用属性setter语法来内联定义它?(对WPF来说还是新手)

//将您的datatemplate设置为资源
//将头模板绑定设置为staticresource

为了更好地理解 您可以在代码中添加groupstyle(XAML就是这么做的)

但是您不能设置GroupStyle

GroupStyle g = new GroupStyle();
ListBox ls = new ListBox();
ls.GroupStyle=g;//error because GroupStyle has only a getter

我刚刚找到了答案——这是因为XAML编译器根据映射到我刚刚记住的内容的属性类型处理元素标记之间的任何内容的方式

如果该属性是ContentControl,那么您在两个标记之间定义的元素将被分配给该Content属性,但是,如果该元素是IList的实例(这就是GroupStyle),那么.NET实际上会在封面下调用.Add()

在本例中,GroupStyle实际上是一个ObservableCollection,因此是一个IList,因此我们实际上没有分配给GroupStyle对象,而是添加到集合中

换句话说,元素标记之间由内容(通过控件的ContentProperty属性映射)表示的属性类型会影响XAML编译器解释它的方式(直接赋值或调用.Add())


您可以选择以下选项:

        <ListBox.GroupStyle>
            <GroupStyle ContainerStyle="{StaticResource listContainerStyle}"/>
        </ListBox.GroupStyle>

而不是

<Style x:Key="listContainerStyle" TargetType="{x:Type GroupItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Expander Header="{Binding Name}" IsExpanded="True">
                    <ItemsPresenter />
                </Expander>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


Avi.

这很有效,谢谢!然而,从XAML的角度来看,为什么我们可以在属性没有setter的情况下使用属性setter语法定义一个与空白内联的GroupStyle呢?我对此感到困惑。如果你也能回答最后一个问题,我会将你的答案标记为解决方案:)这是因为GroupStyle没有setter public observateCollection GroupStyle{get;}(msdn)是的,我知道这一点(我甚至提到它没有属性setter)-那么为什么XAML的属性setter语法有效呢?是的,但您只能通过属性GroupStyle(ContainesStyle,headertemplate…)设置值。当您指定GroupStyle项时,它只是一个获取访问权限,而不是混乱中的一个集合,因为ListBox.GroupStyle属性是GroupStyle的容器
        <ListBox.GroupStyle>
            <GroupStyle ContainerStyle="{StaticResource listContainerStyle}"/>
        </ListBox.GroupStyle>
<Style x:Key="listContainerStyle" TargetType="{x:Type GroupItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Expander Header="{Binding Name}" IsExpanded="True">
                    <ItemsPresenter />
                </Expander>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>