How to dynamically access element names in XAML?


Question

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

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

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:

<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 });
1
15
3/26/2009 9:35:03 AM

Accepted Answer

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

TextBox fieldTB = (TextBox)this.FindName("Field_CompanyName");
43
3/26/2009 9:48:45 AM

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 FindName works by default only for elements declared within XAML.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon