WPF数据表格自动展开第一组

6

我有一个数据网格,其中的itemsource绑定到一个只有一个组的ListCollectionView。

当我填充集合时,我希望第一组自动展开,如何在WPF中编写代码实现这个功能(可以是codebehind或MVVM)?

<DataGrid 
     ItemsSource="{Binding ResultColl}" 
     SelectedItem="{Binding Path=SelectedResultItem, Mode=TwoWay}"
     SelectionMode="Single" IsReadOnly="True" >
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <Expander>
                                    <Expander.Header>
                                        <StackPanel>
                                                <TextBox Text="{Binding Items[0].ID}" />
                                        </StackPanel>
                                    </Expander.Header>
                                    <ItemsPresenter />
                                </Expander>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>

    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=ID}"/>
        <DataGridTextColumn Binding="{Binding Path=Typ}"/>
        <DataGridTextColumn Binding="{Binding Path=Info}"/>
        <DataGridTextColumn Binding="{Binding Path=orderDate, StringFormat={}{0:dd-MM-yyyy}}"/>
    </DataGrid.Columns>
</DataGrid>

在MVVM控制器中:
ListCollectionView tmp = new ListCollectionView(myList);
tmp.GroupDescriptions.Add(new PropertyGroupDescription("ID"));
ResultColl = tmp;
...
ListCollectionView _resultColl;
public ListCollectionView ResultColl
{
    get { return _resultColl; }
    set { _resultColl = value;

        RaisePropertyChanged("ResultColl");
        if (value != null && _resultColl.Count > 0)
            SelectedResultItem = _resultColl.GetItemAt(0) as ItemResult;
    }
}

执行代码时,数据网格填充,第一项被选中,但分组被折叠。

这太模糊了,你到目前为止尝试过什么? - akjoshi
我尝试在设置CollectionView之后设置SelectedItem属性。 - alexn234
2个回答

14
将 IsExpanded 属性添加到您的类中,并在 Expander 上添加绑定:
<Expander IsExpanded="{Binding Items[0].IsExpanded}">

将第一个设置为IsExpanded为true


好的,这个起作用了,我想知道它是否只能在XAML代码中完成。 - alexn234
谢谢!一旦你弄清楚了,它看起来就很明显。 - Arturo Torres Sánchez

2

你可以尝试向你的视图模型添加另一个布尔属性,默认值为true,但第一次使用时切换为false。并将Expander的IsExpanded属性与此绑定,使用OneTime模式。

    public bool IsExpanded
    {
        get
        {
            if (_isExpanded)
            {
                _isExpanded = false;
                return true;
            }
            return false;
        }
    }

Xaml的示例代码如下:

<Expander IsExpanded="{Binding DataContext.IsExpanded, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Mode=OneTime}">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接