Reputation: 1870
I have a list of TextBoxes which are bound to different properties.
<TextBox Text="{Binding Name, Mode=TwoWay,ValidatesOnDataErrors=True, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Margin="5" Width="300" Grid.Column="1" Grid.Row="1" LostFocus="TextBox_Validate"/>
I would like to write ONE handler such as
private void TextBox_Validate(object sender, RoutedEventArgs e)
{
var textBox = (sender as TextBox);
if(textBox!=null)
{
var propertyName = X; // Get propertyName textBox.Text is bound to.
CurrentDataContext.ValidateFields("Name"); // Name in this specific textBox
}
}
Is it possible to get the name of the property so I won't have to write many different methods that do the same thing?
Upvotes: 2
Views: 1747
Reputation: 6103
I think this is what you want:
var expression = textBox.GetBindingExpression(TextBox.TextProperty);
if (expression != null && expression.ParentBinding != null)
{
var propertyName = expression.ParentBinding.Path.Path;
}
Edit
Or you can use BindingOperations.GetBinding
as shown here. I'm not sure if one way is better than the other.
Upvotes: 6
Reputation: 9478
Name the TextBox in xaml, x:Name="MyTextBox"
, then you can check it, textBox.Name == "MyTextBox"
.
Upvotes: 1