2009-03-26 43 views
10

Tôi có một biểu mẫu đầu vào XAML mà người dùng điền vào.Cách truy cập động tên phần tử trong XAML?

Tôi muốn xác thực biểu mẫu này.

Tôi có thông tin trường trong bộ sưu tập mà tôi muốn lặp lại và kiểm tra từng trường.

Nhưng làm cách nào để truy cập tên của trường khi nó nằm trong một chuỗi, ví dụ: khi fieldInformation.FieldName = "CompanyName" Tôi muốn kiểm tra "Field_CompanyName.Text".

Mã giả:

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

Trả lời

37

Mà không phải là chỉ là một cuộc gọi FindName trong bạn mã đằng sau tập tin hoặc tui bỏ lỡ điều gì vậy?

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

Đang hoạt động. Cảm ơn bạn – deanpodgornik

6

Ngoài ra nếu bạn sẵn sàng để thêm các yếu tố giao diện người dùng từ mã phía sau bạn sẽ phải sử dụng các cuộc gọi RegisterName("Field_CompanyName", some_instance) phương pháp như FindName công trình theo mặc định chỉ cho các yếu tố đã tuyên bố trong XAML.

Các vấn đề liên quan