3

我正在尝试创建一个样式,它将为我的 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>

是否有解决此问题的方法,而且,如果此属性没有设置器,那么我们如何首先在 XAML 中使用属性设置器语法对其进行内联定义?(仍然是 WPF 的新手)

4

4 回答 4

3

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

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

在这种情况下,GroupStyle 实际上是一个 ObservableCollection,因此是一个 IList,因此我们实际上并没有分配给 GroupStyle 对象,而是添加到集合中。

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

于 2012-08-19T01:42:38.513 回答
2


您可以执行以下操作:

        <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>

艾维。

于 2014-05-27T12:40:50.100 回答
1
//set you datatemplate as a resource
<DataTemplate x:Key="categoryTemplate">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>


//set header template binding to staticresource
<ListBox Name="lst"> 
   <ListBox.GroupStyle>
      <GroupStyle HeaderTemplate="{StaticResource categoryTemplate}" />
    </ListBox.GroupStyle>
</ListBox>
于 2012-08-18T22:24:57.767 回答
0

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

GroupStyle g = new GroupStyle();
ListBox ls = new ListBox();
ls.GroupStyle.Add(g);

但你不能设置 GroupStyle

GroupStyle g = new GroupStyle();
ListBox ls = new ListBox();
ls.GroupStyle=g;//error because GroupStyle has only a getter
于 2012-08-19T01:13:17.360 回答