如何动态访问 XAML 中的元素名称? [英] How to dynamically access element names in XAML?

查看:26
本文介绍了如何动态访问 XAML 中的元素名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户填写的 XAML 输入表单.

I have a XAML input form which the user fills out.

我想验证此表单.

我有一个集合中的字段信息,我想遍历并检查每个字段.

I have the field information in a collection which I want to loop through and check each field.

但是当字段在字符串中时我如何访问它的名称,例如当 fieldInformation.FieldName = "CompanyName" 我想检查 "Field_CompanyName.Text".

But how do I access the name of the field when it is in a string, e.g. when fieldInformation.FieldName = "CompanyName" I want to check "Field_CompanyName.Text".

伪代码:

foreach (var fieldInformation in _fieldInformations)
{
    if (Field_{&fieldInformation.FieldName}.Text.Length > 2)
    {
        ErrorMessage.Text = String.Format("The length of {0} is too long, please correct.", fieldInformation.FieldName);
        entryIsValid = false;
    }
}

XAML:

<StackPanel Orientation="Horizontal" Margin="10 10 10 0">
    <TextBlock Width="150" Text="Customer ID:"/>
    <TextBox x:Name="Field_CustomerID" Width="150" MaxLength="5" Text=""/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10 10 10 0">
    <TextBlock Width="150" Text="Company Name:"/>
    <TextBox x:Name="Field_CompanyName" Width="150" MaxLength="40" Text=""/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10 10 10 0">
    <TextBlock Width="150"  Text="Contact Name:"/>
    <TextBox x:Name="Field_ContactName" Width="150" MaxLength="30" Text=""/>
</StackPanel>

代码隐藏:

_fieldInformations.Add(new FieldInformation { FieldName = "CustomerID", FieldSize = 5 });
_fieldInformations.Add(new FieldInformation { FieldName = "CompanyName", FieldSize = 40 });
_fieldInformations.Add(new FieldInformation { FieldName = "ContactName", FieldSize = 30 });

推荐答案

这不就是在你的代码隐藏文件中调用 FindName 还是我遗漏了什么?

Isn't that just a FindName call in you code behind file or am I missing something?

TextBox fieldTB = (TextBox)this.FindName("Field_CompanyName");

这篇关于如何动态访问 XAML 中的元素名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆