Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically access element names in XAML?

Tags:

c#

wpf

xaml

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 });
like image 650
Edward Tanguay Avatar asked Mar 26 '09 09:03

Edward Tanguay


2 Answers

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

TextBox fieldTB = (TextBox)this.FindName("Field_CompanyName");
like image 105
sipsorcery Avatar answered Sep 30 '22 13:09

sipsorcery


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.

like image 27
Denis Vuyka Avatar answered Sep 30 '22 12:09

Denis Vuyka