Wpf 数据网格问题

发布于 2024-12-04 10:07:35 字数 4779 浏览 1 评论 0原文

要重现此问题,请添加用户控件,粘贴下面的 xaml,然后将实例添加到窗口。最后将窗口的数据上下文设置为 ADummyDataContext 的实例(也在下面)。

当您第一次运行应用程序时,您应该得到一个包含三个类别的网格,每个类别包含一只猫。如果您单击底部两个类别中的任何一个并单击猫的名称,则会出现一个蓝色行,仅显示猫的名称。

但是,如果单击第一行并单击猫的行,则不会出现蓝色行。 注意:这只在您第一次运行应用程序时发生。一旦您单击任何其他猫,第一类别中的猫就会按预期工作。

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

这是数据上下文类和 Kitten 类。

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

}

我特别想知道你是如何找出问题所在的。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愿得七秒忆 2024-12-11 10:07:35

问题是 DataGrid 中的第一项在首次加载时已被选中。但是,它并未真正被选中,它并未显示为已选中,并且组也未展开。但是,当您第一次单击第一个项目时,DataGrid 无法区分差异,因为 SelectedIndex 已经是 0。这真的很烦人,我注意到类似的行为之前好几次了。

作为解决方法,您可以取消选择 DataGridLoaded 事件中的第一项

<DataGrid Loaded="dataGrid1_Loaded"
          ...>

事件处理程序:请注意 SelectedIndex 为 0

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

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;
}
葮薆情 2024-12-11 10:07:35

非常感谢@Fredrik
这是我的评论之后的代码:

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

此代码还允许根据需要刷新数据

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文