[英]Get XAML controls by their bound properties?
Is there a way to get the controls in XAML using the properties bound to them, 有没有一种方法可以使用绑定到控件的属性来获取XAML中的控件,
something like this: 像这样的东西:
Account acc = GetFromDB(id);
foreach (var prop in acc.GetType().GetProperties())
{
Control control = GetControl(prop.Name);
//Then I want to set properties like Foreground for the control
}
private Control GetControl(string propertyName)
{
//getting the control bound to the propertyName
}
and say that this is XAML code: 并说这是XAML代码:
<Label>Name</Label>
<TextBox Name="txtName"
Grid.Column="1"
Text="{Binding Name}"/>
<Label Grid.Row="1">Debt</Label>
<TextBox Name="txtDebt"
Grid.Column="1"
Grid.Row="1"
Text="{Binding Debt}"/>
<Label Grid.Row="2">Join Date</Label>
<DatePicker Name="dpJoin"
Grid.Column="1"
Grid.Row="2"
Text="{Binding JDate}"/>
Just set x:Name
and find control you need by VisualTreeHelper . 只需设置
x:Name
并通过VisualTreeHelper找到所需的控件即可。 If you need a specific control name, you can bind it like x:Name="{Binding Name}"
如果需要特定的控件名称,则可以像
x:Name="{Binding Name}"
一样绑定它。
public static T GetChildOfType<T>(this DependencyObject depObj)
where T : DependencyObject
{
if (depObj == null) return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}
And here is a sample ho do it by property name: 以下是通过属性名称执行此操作的示例:
public static T FindVisualChildByName<T>(FrameworkElement depObj, string name) where T : FrameworkElement
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i) as FrameworkElement;
if (child != null && child is T && child.Name == name)
return (T)child;
T childItem = FindVisualChildByName<T>(child, name);
if (childItem != null)
return childItem;
}
}
return null;
}
EDIT: 编辑:
There is example how to use this methods. 有示例如何使用此方法。
FindVisualChildByName<T>
method have two parameters, first is the page or control instance where you will seeking for, and second is control name to find on the page. FindVisualChildByName<T>
方法有两个参数,第一个是您要查找的页面或控件实例,第二个是要在页面上查找的控件名称。
Not sure how to get Frame
or page instance in WPF, but in UWP it looks like this: 不确定如何在WPF中获取
Frame
或页面实例,但是在UWP中看起来像这样:
var frame = Window.Current.Content as Frame;
var textBox = VisualHelper.GetChildOfType<TextBox>(frame);
var anotherTextBox = VisualHelper.FindVisualChildByName<TextBox>(frame, "MyTextBox");
Or cast like this: 或像这样铸造:
var obj = VisualHelper.FindVisualChildByName<object>(frame, "MyTextBox");
var type = obj.GetType();
var textBox = System.Convert.ChangeType(obj, type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.