所以,基本上我有一个我在 Datagrid 中跟踪的作业列表。在那个数据网格中,我有一个按钮,我想在作业运行时成为“取消”按钮,否则是“重试”按钮。
所以,我已将按钮添加到我的网格中:
<DataGridTemplateColumn x:Name="JobActionColumn" Header="">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Button Click="JobActionButton_Click" Content="Resend" Name="JobActionButton" Height="18" Width="45" Margin="0,0,0,0" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
在代码中,我将我的对象添加到 ObservableCollection 中以将其添加到网格中:
_jobs.Add(job);
CollectionViewSource jobViewSource = this.FindViewSource("JobViewSource");
jobViewSource.View.Refresh(); // Ensure that the new job appears at the top of the grid.
JobDataGrid.SelectedItem = job;
// Note: The Controller.Completed event handler disposes the controller object.
Controller controller = new Controller(_historyContext);
_controllers.Add(controller);
controller.Completed += Controller_Completed;
controller.Process(job);
GetGridButton("JobActionButton", job).Content = "Cancel";
GetGridButton 为:
private Button GetGridButton(string name, Job job)
{
var selectedRow = (DataGridRow)JobDataGrid.ItemContainerGenerator.ContainerFromItem(job);
return ExtensionMethods.FindVisualChildren<Button>(selectedRow).First(x => x.Name == name);
}
我已经确认GetGridButton适用于已经存在的行。问题是,当您向基础数据集添加新行并调用它时,它找不到DataGridRow。我认为这是因为它尚未创建。因此,查看事件,看起来LoadingRow事件将是一个很好的候选:
private void JobDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
Job job = (Job)e.Row.Item;
if (_controllers.FirstOrDefault(x => x.Job == job) != null)
{
var y = ExtensionMethods.FindVisualChildren<Button>(e.Row);
Button button = ExtensionMethods.FindVisualChildren<Button>(e.Row).First(x => x.Name == "JobActionButton");
button.Content = "Cancel";
}
}
所以,现在有一个DataGridRow对象可以传递给FindVisualChildren,但它仍然没有找到任何按钮。那么,有什么方法可以让我在添加的行上访问此按钮?