通过绑定属性获取XAML控件?

时间:2017-07-27 11:25:32

标签: c# wpf xaml

有没有办法使用绑定到它们的属性来获取XAML中的控件,

类似的东西:

 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
 }

并说这是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}"/>

1 个答案:

答案 0 :(得分:0)

只需设置x:Name并找到VisualTreeHelper所需的控件。 如果您需要特定的控件名称,可以将其绑定为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;
}

这是一个样本,按属性名称执行:

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

修改

有关如何使用此方法的示例。

FindVisualChildByName<T>方法有两个参数,第一个是您要寻找的页面或控件实例,第二个是在页面上查找的控件名称。

不确定如何在WPF中获取Frame或页面实例,但在UWP中它看起来像这样:

var frame = Window.Current.Content as Frame;
var textBox = VisualHelper.GetChildOfType<TextBox>(frame);
var anotherTextBox = VisualHelper.FindVisualChildByName<TextBox>(frame, "MyTextBox");

或者像这样投射:

var obj = VisualHelper.FindVisualChildByName<object>(frame, "MyTextBox");
var type = obj.GetType();
var textBox = System.Convert.ChangeType(obj, type);