2011-05-24 123 views
2

我有一個綁定到不同屬性的TextBoxes列表。TextBox - 綁定屬性名稱

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

是否有可能獲得屬性的名稱,這樣我就不用寫做同樣的事情很多不同的方法呢?

回答

6

我想這是你想要什麼:

var expression = textBox.GetBindingExpression(TextBox.TextProperty); 
if (expression != null && expression.ParentBinding != null) 
{ 
    var propertyName = expression.ParentBinding.Path.Path; 
} 

編輯

或者你可以使用BindingOperations.GetBinding如圖所示here。我不確定一種方式比另一種更好。

+0

太棒了!正是我需要的! – 2013-02-27 07:56:50

1

將該文本框命名爲xaml,x:Name="MyTextBox",然後您可以檢查它,textBox.Name == "MyTextBox"

+0

我不認爲這是最好的解決方案。如果有幾個領域被綁定到同一個財產,我將不得不制定一些模式,即。 'fieldType_propertyName'命名所有字段。 – Luke 2011-05-24 22:57:18

+0

哦,是的,我錯了,綁定屬性的名稱,我的壞。 – 2011-05-25 02:37:42

相關問題