C# 如何动态访问 XAML 中的元素名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/685077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:23:03  来源:igfitidea点击:

How to dynamically access element names in XAML?

c#wpfxaml

提问by Edward Tanguay

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

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

I want to validate this form.

我想验证这个表格。

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

我有一个集合中的字段信息,我想循环并检查每个字段。

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".

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

Pseudocode:

伪代码:

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:

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>

Code-Behind:

代码隐藏:

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

采纳答案by sipwiz

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

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

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

回答by Denis Vuyka

Also if you are willing to add UI elements from code behind you will have to use the RegisterName("Field_CompanyName", some_instance)method call as FindNameworks by default only for elements declared within XAML.

此外,如果您愿意从后面的代码中添加 UI 元素,您将不得不使用RegisterName("Field_CompanyName", some_instance)方法调用作为FindName默认情况下仅适用于在 XAML 中声明的元素。