WPF DataGridCell LostFocus事件停止在DataGridRow冒泡

时间:2013-01-14 06:47:02

标签: wpf datagrid focus routed-events

我无法理解下面的代码是怎么回事。

这是一个相对简单的wpf数据网格,它显示ObservableCollection个对象。如果我选择一行,然后按删除键,则LostFocus会触发DataGridCell事件。使用Snoop,我可以查看接收此路由(冒泡)事件的元素。它从DataGridCell开始,在视觉树上冒泡,直到它到达DataGridRow,然后停止(这在Snoop中显而易见,显示未处理和处理的事件)。

我对冒泡事件的理解让我相信LostFocus事件应该一直冒泡到父窗口。

是什么给出了?

    <Window x:Class="ApplicationName.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
        <Grid x:Name="_grid">
            <DataGrid
                ItemsSource="{Binding Items}"
                AutoGenerateColumns="False"
                HeadersVisibility="Column"
                CanUserDeleteRows="True"
                SelectionUnit="FullRow">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path=FirstName}"
                                Header="FirstName"/>
                    <DataGridTextColumn Binding="{Binding Path=LastName}"
                                Header="LastName"/>
                    <DataGridTextColumn Binding="{Binding Path=Information}"
                                Header="Information"/>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>

代码隐藏:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModel();
        }
    }

    public class ViewModel
    {
        public ObservableCollection<Person> _items = new ObservableCollection<Person>();

        public ViewModel()
        {
            _items.Add(new Person() { FirstName = "Homer", LastName = "Simpson", Information = "Father" });
            _items.Add(new Person() { FirstName = "Bart", LastName = "Simpson", Information = "Son" });
            _items.Add(new Person() { FirstName = "Santa's", LastName = "Little Helper", Information = "Dog" });

        }

        public ObservableCollection<Person> Items
        {
            get { return _items; }
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Information { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

如果父窗口的LostFocus事件触发,则表示焦点不再位于父窗口中。你期待这种行为吗?我认为这不是你的情况。 DataGridRow失去焦点,DataGridCells失去焦点,但不是父窗口。