WPF:隐式 Theme/Style:来自代码 cs 的 xaml/resource 中的访问控制

WPF: Implicit Theme/Style: Access control in xaml/resource from code cs

我正在使用隐式主题设计网格组件的样式,网格上方有一些按钮,例如工具栏。我想访问这些按钮之一。我创建了一个需要 FrameworkElement 的方法,我打算使用该按钮,但我无法访问。我试过这个:How do I access an element of a control template from within code-behind,但它只在用户控件和它的 .cs 使用时有效。

有没有办法使用隐式主题来做到这一点?

XAML 和 C# 可能会因平台而略有不同(Windows Phone、Windows 10、Windows 7、Silverlight、WPF ).这是如何在 Windows 10.

上实现的
public static class AppHelpers
{
    public static List<T> GetVisualChildCollection<T>(object parent) where T : Control
    {
        List<T> visualCollection = new List<T>();
        GetVisualChildCollection((DependencyObject)parent, visualCollection);
        return visualCollection;
    }

    private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Control
    {
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < count; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child is T)
            {
                visualCollection.Add(child as T);
            }
            else if (child != null)
            {
                GetVisualChildCollection(child, visualCollection);
            }
        }
    }
}

只是..

var buttonsInsideMyGrid = AppHelpers.GetVisualChildCollection<Button>(YourGridName);

我发现了另一种方法。

在您的 XAML 样式中,您设置组件(在我的例子中是一个按钮,但它可以是您需要的任何其他组件),如下所示:

<Button Content="My Button" x:Name="myButton" />

然后,在你的 .cs class(在我的例子中是一个网格,我在它的顶部添加了一个按钮)你这样做:

[TemplatePart(Name = "myButton", Type = typeof(Button))]
public class MyStylizedGrid : RadGridView
{
Button _btn;

// here the constructor and other methods you're using


//Then you use the OnApplyTemplate method to get that component you need 
public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    _btn = GetTemplateChild("myButton") as Button;
}

}