从 (对象发送方,RoutedEventArgs e) 获取列名
本文关键字:获取 RoutedEventArgs 对象 | 更新日期: 2023-09-27 17:55:43
我想像在松散焦点方法上获取单元格内容一样获取单元格的列名。我可以获取内容,但不能获取列标题。
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>
获取列标题
弗雷德里克已经在这里提供了您需要的东西。基本上,您需要获取 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);
我不太确定你的情况。
更新了 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