Hi,
When dealing with UI validation functions I’ve found that I need to get a good looking, descriptive name for my UI elements: textboxes, comboboxes etc.. and so if that elements have labels with target property so the rest is quite simple:
private string GetLabelTextForControl(DependencyObject targetElement, DependencyObject searchIn)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(searchIn); i++)
{
DependencyObject v = VisualTreeHelper.GetChild(searchIn, i);
Label childVisual = v as Label;
if (childVisual != null)
{
if (childVisual.Target == targetElement)
{
return childVisual.Content.ToString();
}
}
else
{
if (VisualTreeHelper.GetChildrenCount(v) > 0)
{
string respValue = GetLabelTextForControl(targetElement, v);
if (!string.IsNullOrEmpty(respValue))
{
return respValue;
}
}
}
}
return string.Empty;
}
It’s quick and dirty but it works. The parameters are: the control which name you are searching and the panel, user control or window in which you are searching.
It works if you have Target property set e.g.:
<Label Target="{Binding ElementName=txtBox}" Content="{Binding Path=Caption, ElementName=me}" />
<TextBox x:Name="txtBox" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" TextWrapping="Wrap"/>
So it’s just a quick answer to a question: How to get labels for UI Controls in WPF, but I’d gladly invite cleaner solution.
Advertisement