6

我有一个数据网格,其中 itemsource 绑定到一组 ListCollectionView。当我填充集合时,我希望自动将第一组视为扩展,如何在 wpf(代码隐藏或 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;
    }
}

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

4

2 回答 2

14

将 IsExpanded 属性添加到您的类并将绑定添加到 Expander:

<Expander IsExpanded="{Binding Items[0].IsExpanded}">

将 IsExpanded for first 设置为 true

于 2013-01-14T11:38:19.903 回答
2

您可以尝试将另一个 bool 属性添加到您的视图模型中,默认为 true,但在第一次使用时切换为 false。并使用 OneTime 模式将 Expander 的 IsExpanded 属性绑定到此。

    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}">
于 2014-09-30T14:28:24.993 回答