如何解决TextBox-绑定的属性名
| 我有一个绑定到不同属性的TextBoxes列表。<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\"/>
我想写一个像
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
}
}
是否有可能获取属性的名称,这样我就不必编写许多不同的方法来执行相同的操作?
解决方法
我认为这是您想要的:
var expression = textBox.GetBindingExpression(TextBox.TextProperty);
if (expression != null && expression.ParentBinding != null)
{
var propertyName = expression.ParentBinding.Path.Path;
}
编辑
或者,您可以按如下所示使用BindingOperations.GetBinding
。我不确定一种方法是否比另一种更好。
,用xaml将文本框命名为x:Name=\"MyTextBox\"
,然后可以将其命名为textBox.Name == \"MyTextBox\"
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。