wpf datagrid cell 设置焦点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了wpf datagrid cell 设置焦点相关的知识,希望对你有一定的参考价值。

在wpf中datagrid 通过代码设置某一行某一列的焦点并且选中状态,也就是将光标的焦
点指定单元格里。

参考技术A Excel的导出一般采取的方式是获取数据源的数据,然后对数据进行处理,形成CAS字符串的形式导出.具体代码(来自网站codeproject,具体可以搜一下,适应与silverlight对wpf大同小异,请适当修改一下!):
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Controls;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Xml.Linq;

public static class DataGridExtensions

public static void Export(this DataGrid dg)

ExportDataGrid(dg);


public static void ExportDataGrid(DataGrid dGrid)

SaveFileDialog objSFD = new SaveFileDialog() ;
if (objSFD.ShowDialog() == true)

string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
StringBuilder strBuilder = new StringBuilder();
if (dGrid.ItemsSource == null) return;
List<string> lstFields = new List<string>();
if (dGrid.HeadersVisibility == DataGridHeadersVisibility.Column || dGrid.HeadersVisibility == DataGridHeadersVisibility.All)

foreach (DataGridColumn dgcol in dGrid.Columns)
lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat));
BuildStringOfRow(strBuilder, lstFields, strFormat);

foreach (object data in dGrid.ItemsSource)

lstFields.Clear();
foreach (DataGridColumn col in dGrid.Columns)

string strValue = "";
Binding objBinding = null;
if (col is DataGridBoundColumn)
objBinding = (col as DataGridBoundColumn).Binding;
if (col is DataGridTemplateColumn)

//This is a template column... let us see the underlying dependency object
DependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent();
FrameworkElement oFE = (FrameworkElement)objDO;
FieldInfo oFI = oFE.GetType().GetField("TextProperty");
if (oFI != null)

if (oFI.GetValue(null) != null)

if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null)
objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding;



if (objBinding != null)

if (objBinding.Path.Path != "")

PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);
if (pi != null) strValue = pi.GetValue(data, null).ToString();

if (objBinding.Converter != null)

if (strValue != "")
strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
else
strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();


lstFields.Add(FormatField(strValue,strFormat));

BuildStringOfRow(strBuilder, lstFields, strFormat);

StreamWriter sw = new StreamWriter(objSFD.OpenFile());
if (strFormat == "XML")

//Let us write the headers for the Excel XML
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">");
sw.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
sw.WriteLine("<Author>Arasu Elango</Author>");
sw.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>");
sw.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>");
sw.WriteLine("<Company>Atom8 IT Solutions (P) Ltd.,</Company>");
sw.WriteLine("<Version>12.00</Version>");
sw.WriteLine("</DocumentProperties>");
sw.WriteLine("<Worksheet ss:Name=\"Silverlight Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
sw.WriteLine("<Table>");

sw.Write(strBuilder.ToString());
if (strFormat == "XML")

sw.WriteLine("</Table>");
sw.WriteLine("</Worksheet>");
sw.WriteLine("</Workbook>");

sw.Close();


private static void BuildStringOfRow(StringBuilder strBuilder, List<string> lstFields, string strFormat)

switch (strFormat)

case "XML":
strBuilder.AppendLine("<Row>");
strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));
strBuilder.AppendLine("</Row>");
break;
case "CSV":
strBuilder.AppendLine(String.Join(",", lstFields.ToArray()));
break;


private static string FormatField(string data, string format)

switch (format)

case "XML":
return String.Format("<Cell><Data ss:Type=\"String\"></Data></Cell>", data);
case "CSV":
return String.Format("\"\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));

return data;

WPF DataGrid 全行编辑

【中文标题】WPF DataGrid 全行编辑【英文标题】:WPF DataGrid Full Row Editing 【发布时间】:2011-08-23 22:35:38 【问题描述】:

我有一个 WPF 数据网格,可以满足我的需求,但每行中有两个单元格可以编辑。是否可以在编辑行时将这两行都置于编辑模式,然后在行编辑结束/行失去焦点时触发更新?目前,在编辑每个单元格后,RowEditEnding 会触发,用户必须等待 UI 在提交后重绘。我使用的代码是:

 private bool isManualEditCommit;
 private void dg_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        
            if(e.EditAction!= DataGridEditAction.Commit)
                return;
            var newProd = dgLists.SelectedItem as IProduct;
            if(newProd==null)
                return;
                    worker = new BackgroundWorker();
                    worker.DoWork += (s, dwe) =>
                    
            ... commit update
                    ;
                    worker.RunWorkerCompleted += (s, rwe) =>
                    
                        ... refresh grid
                    ;
                    worker.RunWorkerAsync();
        
    /// <summary>
    /// Commits edits when a cell edit ends.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Controls.DataGridCellEditEndingEventArgs"/> instance containing the event data.</param>
    private void dg_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
        if (e.EditAction == DataGridEditAction.Commit)
        
            if (!isManualEditCommit)
            
                isManualEditCommit = true;
                DataGrid grid = (DataGrid) sender;
                grid.CommitEdit(DataGridEditingUnit.Row, true);
                isManualEditCommit = false;
            
        

【问题讨论】:

【参考方案1】:

我退出使用 DataGrid 进行编辑。我使用 ListView 然后提供一个 GridView 作为 ListView.View。在 GridView 中,您可以使用 CellTemplates 创建 GridViewColumns。每个 GridView 行的最后一列是删除该行的按钮。我不支持浏览和编辑模式,只支持编辑模式。应用程序运行得更加流畅,我没有任何与使用 DataGrid 相关的头疼问题。

【讨论】:

【参考方案2】:

整行编辑是默认功能。每次单元格编辑都会触发更新的唯一原因是您已经实现了 dg_cellEditEnding 方法。

【讨论】:

但并非所有单元格都进入编辑模式。每个单元格在获得焦点时都会显示它的 CellEditingTemplate,但该行中的其余单元格都有其标准的、不可编辑的控件。

以上是关于wpf datagrid cell 设置焦点的主要内容,如果未能解决你的问题,请参考以下文章

WPF,通过修改dataGrid的cell的style,改变选中行失去焦点时的颜色 4.0可用

当 SelectionMode 设置为 Cell 时,如何突出显示 WPF DataGrid 中的一行

wpf datagrid怎么得到焦点?用datagrid.focus()不行

wpf datagrid怎么得到第一项焦点?然后在方向键上下移动

wpf datagrid 单元格如何默认单击一次点中

使按钮在 DataGrid 中可见