Wpf DataGrid issue

与世无争的帅哥 提交于 2019-12-10 13:00:05

问题


To reproduce this issue, Add a user control, paste in the xaml below and then add an instance to a window. Finally set the window's datacontext to an instance of ADummyDataContext (also below)

When you run the application for the first time, you should get a grid with three categories each containing one cat. If you click on either of the bottom two categories and click on a cat name, a blue row will appear showing just the cat's name.

However, if you click the first row and click the cat's row, the blue row will not appear. NOTE: This only happens the first time you run the application. As soon as you click on any other cat the cat in the first category will work as expected.

<UserControl x:Class="WpfUserControls.SimpleGridControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Background="#FFE46400">
<Grid Margin="2,2,2,2">
    <Grid.RowDefinitions>
        <RowDefinition Height="26" MaxHeight="26" MinHeight="26" />
        <RowDefinition />
        <RowDefinition Height="26" MaxHeight="26" MinHeight="26" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <ToolBar Grid.Row="0">
        <Button Content="Button" Name="button1" VerticalAlignment="Center" Width="75" />
        <Button Content="Button" Name="button2" VerticalAlignment="Center" Width="75" />
    </ToolBar>
    <DataGrid CanUserAddRows="False" ItemsSource="{Binding Path=KittensView}"  AutoGenerateColumns="True" Grid.Row="1"  HorizontalAlignment="Stretch" Name="dataGrid1" VerticalAlignment="Stretch">
        <DataGrid.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" />
                        </StackPanel>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <Expander>
                                        <Expander.Header>
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding Path=Name}" Margin="0,0,5,0"/>
                                                <TextBlock Text="{Binding Path=ItemCount}"/>
                                                <TextBlock Text=" Items"/>
                                            </StackPanel>
                                        </Expander.Header>
                                        <ItemsPresenter />
                                    </Expander>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </DataGrid.GroupStyle>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <StackPanel Background="LightBlue" Orientation="Horizontal" >
                    <!-- <Image Height="32" Width="32" Source="/WpfUserControls;component/cat.png"></Image> -->
                    <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Height ="20" Text="{Binding Path=Name}"/>
                </StackPanel>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>
    <StatusBar Grid.Row="2"></StatusBar>

</Grid>
</UserControl>

And here is the data context class and a Kitten class.

    public class ADummyDataContext
{
    public List<Kitten> Kittens { get; set; } 

    public ADummyDataContext()
    {
        Kittens = new List<Kitten>
                      {
                          new Kitten {Color = "Orange", Name = "Alfie", Weight=6, Sex="Male"},
                          new Kitten {Color = "Black and White", Name = "Smudge", Weight = 4, Sex="Female"},
                          new Kitten {Color = "Grey", Name = "Charlotte", Weight = 5, Sex="Female"}
                      };
        KittensView = new ListCollectionView(Kittens);
        KittensView.GroupDescriptions.Add(new PropertyGroupDescription("Weight"));
    }

    public ListCollectionView KittensView { get; set; }
}

public class Kitten
{
    public string Name { get; set; }
    public string Color { get; set; }
    public int Weight { get; set; }
    public string Sex { get; set; }

}

I would be particularly interested to know how you go about figuring out what the problem is here.

Thanks


回答1:


The problem is that the first item in the DataGrid is already selected when it's first loaded. However, it isn't really selected, it doesn't appear selected and group isn't expanded. But when you click on the first item for the first time, the DataGrid can't tell the difference since SelectedIndex was already 0. This is really annoying and I noticed similar behavior several times earlier.

As a workaround, you can unselect the first item in the Loaded event of the DataGrid

<DataGrid Loaded="dataGrid1_Loaded"
          ...>

Event handler: Notice that the SelectedIndex is 0

private void dataGrid1_Loaded(object sender, RoutedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    dataGrid.SelectedItem = null;
}



回答2:


Thanks a lot @Fredrik here is the code following my comment:

XAML:

<DataGrid SelectionChanged="DataGrid_SelectionChanged">

codebehind.cs:

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    dataGrid.SelectionChanged -= DataGrid_SelectionChanged;
    dataGrid.SelectedItem = null;
    dataGrid.SelectionChanged += DataGrid_SelectionChanged;
}

this code also allow to refresh data as many as you want



来源:https://stackoverflow.com/questions/7415988/wpf-datagrid-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!