I'm styling a Grid component using implict theme and there is some buttons above the grid, like a toolbar. I would like to access one of these buttons. I've created a method that requires a FrameworkElement and I intend to use the button, but I can't access. I have tried this one: How do I access an element of a control template from within code-behind , but it only works when a user control and it's .cs is used.
Is there a way of doing this using implicit theme?
XAML and C# could work a little different depending at the platform (Windows Phone, Windows 10, Windows 7, Silverlight, WPF). Here is how this could be reached on 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);
}
}
}
}
Just..
var buttonsInsideMyGrid = AppHelpers.GetVisualChildCollection<Button>(YourGridName);
I found out another way of doing this.
In your XAML style you set you component (in my case is a button, but it can be any other component you need) like this:
<Button Content="My Button" x:Name="myButton" />
Then, on your .cs class (in my case is a grid, where I'm adding a button on the top of it) you do like this:
[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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.