我使用此方法列出usercontrol的所有按钮:
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
int NbChild = VisualTreeHelper.GetChildrenCount(depObj);
for (int i = 0; i < NbChild; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childNiv2 in FindVisualChildren<T>(child))
{
yield return childNiv2;
}
}
}
}
public static void ImplementShortCut(ContentControl page)
{
List<Button> ListButton = new List<Button>();
ListButton = FindVisualChildren<Button>(page).ToList();
....
}
除了 DataGridTemplateColumn.CellTemplate
内的按钮外,它运行良好<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="Btn_Edit"
Click="Btn_EditTest_Click"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
' VisualTreeHelper.GetChild '似乎无法在datagrid项目中找到控件。
答案 0 :(得分:0)
我的班级
public class ShortCutUtils
{
public static void ImplementShortCut(ContentControl page)
{
List<Button> ListButton = new List<Button>();
ListButton = FindVisualChildren<Button>(page).ToList();
...
}
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
int NbChild = VisualTreeHelper.GetChildrenCount(depObj);
for (int i = 0; i < NbChild; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childNiv2 in FindVisualChildren<T>(child))
{
yield return childNiv2;
}
}
}
}
}
TestPage XAML
<DataGrid Grid.Row="0" x:Name="Dg_Test"
Margin="2"
AutoGenerateColumns="False"
SelectedCellsChanged="dg_Test_SelectionChanged"
SelectionMode="Single"
MouseLeftButtonDown="Dg_TestMouseClick"
RowDetailsVisibilityMode="{Binding RowDetailsVisible}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
Style="{StaticResource DatagridDesktopStyle}">
<DataGrid.Columns>
...
<DataGridTemplateColumn Width="auto" IsReadOnly="True" Header="">
DataGridTemplateColumn.HeaderTemplate>
...
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="Btn_Edit"
Click="Btn_EditTest_Click"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
TestPage代码
public partial class TestPage : UserControl
{
public TestPage()
{
InitializeComponent();
this.Loaded += TestListPage_Loaded;
this.DataContext = this;
}
private async void TestListPage_Loaded(object sender, RoutedEventArgs e)
{
ShortCutUtils.ImplementShortCut(this);
}
}
答案 1 :(得分:0)
假设 swiszcz ,在调用&#39; ShortCutUtils.ImplementShortCut(this)&#39;时,所有控件都未完成加载。 &#39; 加载&#39;结束时的方法。为了解决这个问题,我将此方法置于低优先级&#39;调用&#39;
Application.Current.Dispatcher.Invoke(() =>
{ShortCutUtils.ImplementShortCut (this);
}, DispatcherPriority.Render);
它工作正常!非常感谢你