繁体   English   中英

WPF:隐式主题/样式:xaml /来自代码cs的资源中的访问控制

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

我正在使用隐式主题设置Grid组件的样式,并且在网格上方有一些按钮,例如工具栏。 我想访问这些按钮之一。 我创建了一个需要FrameworkElement的方法,并且打算使用该按钮,但无法访问。 我已经尝试过以下方法: 我如何从代码隐藏中访问控件模板的元素 ,但仅在使用用户控件及其.cs时才起作用。

有没有一种使用隐式主题的方法?

根据平台(Windows Phone,Windows 10,Windows 7,Silverlight,WPF)的不同,XAML和C#的工作方式可能有所不同。 这是在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类(在我的例子中是一个网格,在该网格的顶部添加一个按钮)上,您会这样:

[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;
}

}

暂无
暂无

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

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