问题描述
我有一些DataGrid,数据绑定到我的集合( INotifyCollectionChanged
)。
I have some DataGrid, data is bind to my collection (INotifyCollectionChanged
).
记录必须是创建新的时预填充。因此,我禁止添加dataGrid( CanUserAddRows = False
)并处理 PreviewKeyUp事件(当用户按ctrl + N时,执行方法 CreateRecord –通知添加的新记录。)
Records has to be prefilled when you create new one. So I disabled adding in dataGrid (CanUserAddRows="False"
) and handle "PreviewKeyUp" event (when user press ctrl+N, execute method "CreateRecord" – notify of added new record).
这种情况下工作正常……几乎。
This scenario work perfectly… almost.
PreviewKeyUp 。但是,如果我没有任何记录,就没有焦点,事件也永远不会被触发。
PreviewKeyUp
was fired only if some element in grid is focused (e.g. DataGridRow). But if I don’t have any record, there is no focus and event was never fired.
所以我的问题是:能否以某种方式处理键ctrl + N当DataGrid为空时?例如。触发Focusable或类似的事情。
So my question is: If is it possible to somehow handle keys ctrl+N when DataGrid is empty? E.g. trigging Focusable or something like this.
另一个解决方法是捕获以某种方式添加行并填充必填字段,但是...
标准的NewItemPlaceholder会很好,但是EditableItems使用没有参数的项目构造函数。
这是我无法使用的另一种想法(或者我只是不知道如何使用:D)
Another workaround would be to "catch" somehow adding row and fill required fields, but...
Standard NewItemPlaceholder will be fine, but EditableItems use item constructor with no parameters.
And this is another think I couldn't use (or I just don't known how :D)
必须使用预定义的值(例如createdUserId)创建我的数据。
My Data has to be created with predefined values (like createdUserId).
某些代码澄清:
public MyItemsCollection Items { get; set; }
public MyItemType CreateRecord()
{
MyItemType item = new MyItemType(userId);
item.InitValues();
Items.Add(item);
return item;
}
/********/
public void dataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.N && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
CreateRecord();
e.Handled = true;
}
}
<DataGrid AutoGenerateColumns="False" Name="dataGrid" ItemsSource="{Binding Items}"
CanUserSortColumns="False" CanUserDeleteRows="True"
CanUserAddRows="False" PreviewKeyUp="dataGrid_PreviewKeyUp">
有人知道吗?
推荐答案
为什么不尝试将其附加到Window的PreviewKeyUp ...上,如果数据网格中没有记录,则强制使用它...或者只是强制使用它。只要该人处于该表单中,则如果该表单或网格具有此类按键的焦点,则可能意味着要这样做。
Why not try to attach to the Window's PreviewKeyUp... and if no record in the data grid, force it... or just force it regardless. As long as the person is in that form, it could be implied to do it if the form OR the grid has the focus for such key press.
这篇关于WPF DataGrid,处理键并且没有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!