【问题标题】:TextBox - Bound Property NameTextBox - 绑定属性名称
【发布时间】:2011-09-01 07:18:31
【问题描述】:

我有一个绑定到不同属性的文本框列表。

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

是否可以获取属性的名称,这样我就不必编写许多不同的方法来做同样的事情?

【问题讨论】:

    标签: c# silverlight data-binding binding


    【解决方案1】:

    我想这就是你想要的:

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

    编辑

    或者您可以使用BindingOperations.GetBinding,如图所示here。我不确定一种方法是否比另一种更好。

    【讨论】:

    • 太棒了!正是我需要的!
    【解决方案2】:

    在 xaml 中命名 TextBox,x:Name="MyTextBox",然后你可以检查它,textBox.Name == "MyTextBox"。

    【讨论】:

    • 我认为这不是最好的解决方案。如果很少有字段绑定到同一属性,我将不得不制定一些模式,即。 fieldType_propertyName 为所有字段命名。
    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多