简体   繁体   English

如何访问ItemsControl-> ItemTemplate-> DataTemplate-> StackPanel中的按钮? WPF的C#

[英]How to access the button inside ItemsControl->ItemTemplate->DataTemplate->StackPanel? wpf c#

How can I get button in code behind from this structure in xaml? 如何从xaml中的此结构获取代码背后的按钮?

<ItemsControl BorderBrush="Black" BorderThickness="2" Name="cat1" ItemsSource="{Binding Questions[0]}" Margin="65,0,0,165">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Name="sp1">
                        <Button Width="60" Content="{Binding Points}" Height="30" Tag="{Binding Id}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}"  Command="{Binding ElementName=cat1,  Path=DataContext.QuestionButtonClick}">

                        </Button>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
  • I tried to get stackpanel with name 我试图获得名称为stackpanel的东西

  • tried to get it from many foreach es 试图从许多foreach获取它

You can use VisualTreeHelper to get the element on the current visual tree of your window. 您可以使用VisualTreeHelper在窗口的当前可视树上获取元素。

For convenience, you can use the following extension method that can finds all children elements with the specified type or condition recursively on the visual tree. 为了方便起见,可以使用以下扩展方法,该方法可以在可视树上递归查找具有指定类型或条件的所有子元素。

public static class DependencyObjectExtensions
{
    public static IEnumerable<T> GetChildren<T>(this DependencyObject p_element, Func<T, bool> p_func = null) where T : UIElement
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(p_element); i++)
        {
            UIElement child = VisualTreeHelper.GetChild(p_element, i) as FrameworkElement;
            if (child == null)
            {
                continue;
            }

            if (child is T)
            {
                var t = (T)child;
                if (p_func != null && !p_func(t))
                {
                    continue;
                }

                yield return t;
            }
            else
            {
                foreach (var c in child.GetChildren(p_func))
                {
                    yield return c;
                }
            }
        }
    }
}

Then when the window is loaded, you can get all the buttons like this: 然后,在加载窗口时,您将获得如下所有按钮:

var buttons = this.cat1.GetChildren<Button>().ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM