亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Key.Down事件上的DataGrid中選擇第一項(在列表中)

在Key.Down事件上的DataGrid中選擇第一項(在列表中)

C#
UYOU 2021-04-09 17:19:49
當用戶按下箭頭鍵時,這是Key.Down事件,我正在嘗試在Datagrid中選擇第一行。它現在可以正常工作,但是即使我通過索引[0],它仍會以某種方式選擇第二行...我創建了SelectRowByIndex方法,該方法應該選擇Datagrid的第一行,如下所示:private static void SelectRowByIndex(DataGrid dataGrid, int rowIndex)        {            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.FullRow))                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to FullRow.");            if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))                throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));            dataGrid.SelectedItems.Clear();            object item = dataGrid.Items[rowIndex];            dataGrid.SelectedItem = item;            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;            if (row == null)            {                //Moram dodati BillItemTemp u slu?aju da je virtualized away                dataGrid.ScrollIntoView(item);                row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;            }            if (row != null)            {                DataGridCell cell = GetCell(dataGrid, row, 0);                if (cell != null)                    cell.Focus();            }        }          之后,在加載表單時,我在構造函數中調用了它: this.PreviewKeyDown += (s, e) => {        if (e.Key == Key.Down && dtgProducts.HasItems)          SelectRowByIndex(dtgProducts, 0); };但是以某種方式選擇第二行?而不是第一個...怎么來的?而且,當我不斷按下Key.Down時不要一直選擇同一行,我需要確保自己的安全。
查看完整描述

2 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

您正在與WPF戰斗。你不會贏。用這種方法填充時,WPF不喜歡它。它通常希望您使用數據綁定。


您可以使用viewmodels和databinding來做到這一點(如果您有興趣的話,可以添加此答案的先前版本),但這并不困難。


private static void SelectRowByIndex(DataGrid dataGrid, int rowIndex)

{

    //  Or set this in XAML better yet

    dataGrid.IsSynchronizedWithCurrentItem = true;


    var view = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);


    view.MoveCurrentToPosition(rowIndex);

}


查看完整回答
反對 回復 2021-04-17
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

假設您的意思是使用向下箭頭鍵,則您做出了一個非常糟糕的選擇。采取任何數據網格。
單擊一行。
按向下箭頭。
焦點移至下一行。

查看完整回答
反對 回復 2021-04-17
  • 2 回答
  • 0 關注
  • 173 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號