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

时间:2015-09-22 18:25:05

标签: c# wpf xaml themes styling

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

有没有办法使用隐式主题?

2 个答案:

答案 0 :(得分:1)

根据平台(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);

答案 1 :(得分:0)

我发现了另一种方法。

在你的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;
}

}