2015-06-11 93 views
0

我想獲得單元格的列名,就像我在鬆散焦點方法上處理它的內容一樣。我可以獲取內容,但不能獲取列標題。從(對象發件人,RoutedEventArgs e)獲取列名稱

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>

回答

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

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); 

或文本框

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

開始我並不完全確定你的場景。

+0

仍然收到空引用。是的即時通訊使用發件人獲取當前列標題名稱 –

+0

@ kay-B您的發件人的類型是什麼?它是一個文本框? –

+0

添加xaml代碼 –