从(object sender,RoutedEventArgs e)

时间:2015-06-11 12:28:43

标签: c# wpf wpfdatagrid

我想获取单元格的列名称与我在松散焦点方法上的内容相同。我可以获取内容而不是列标题。

private void lostFocus(object sender, RoutedEventArgs e)
{
    var jj = sender as DataGridColumnHeader;          
    var box = sender as TextBox;          

    if (box != null && box.Text != "0")
    {
        var ff =  jj.Column.Header.ToString();          
        if (ff == "column1") { amount1 = Int32.Parse(box.Text); }
        if (ff == "column2") { amount2 = Int32.Parse(box.Text); }
        if (ff == "column3") {amount3 = Int32.Parse(box.Text); }
    }
    else
    {

    }
}

xaml代码



<toolkit:DataGridTemplateColumn Header="column1" Width="8*">
  <toolkit:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <TextBox Padding="0" LostFocus="OnGotFocus" GotFocus="OnGotFocus" />
    </DataTemplate>
  </toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

Getting column header

Fredrik已在此处提供您所需要的内容。基本上,您需要在DataGrid中存在DataGridColumnHeader类型的所有子级。检查列引用,然后获取标题。

此外,我发现你从发件人那里获得了DataGridColumnHeader。为了访问DataGrid对象,您可以使用辅助方法:

    public static T FindParent<T>(DependencyObject child) where T : DependencyObject
    {
        //get parent item
        DependencyObject parentObject = VisualTreeHelper.GetParent(child);

        //we've reached the end of the tree
        if (parentObject == null) return null;

        //check if the parent matches the type we're looking for
        T parent = parentObject as T;
        if (parent != null)
            return parent;
        else
            return FindParent<T>(parentObject);
    }

像这样使用:

DataGrid parentGrid = FindParent<DataGrid>(sender as DataGridColumnHeader );

或从TextBox开始

DataGrid parentGrid = FindParent<DataGrid>(sender as TextBox);

我不确定你的情况。

答案 1 :(得分:0)

更新了Xamal ...将文本框名称设置为与标题名称相同

<toolkit:DataGridTemplateColumn Header="column1" Width="8*">
  <toolkit:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <TextBox Padding="0" Name="column1" LostFocus="OnGotFocus" />
    </DataTemplate>
  </toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>

然后从我的发件人那里得到了名字......简单的工作

private void lostFocus(object sender, RoutedEventArgs e)
{      
    var box = sender as TextBox;          
    if (box != null && box.Text != "0")
    {
        var name = box.Name.ToString();

        if (name == "column1") { amount1 = Int32.Parse(box.Text); }
        if (name == "column2") { amount2 = Int32.Parse(box.Text); }
        if (name == "column3") {amount3 = Int32.Parse(box.Text); }
    }
    else
    {

    }
}

感谢您的帮助https://stackoverflow.com/users/2047469/olaru-mircea