【问题标题】:WPF: Get Property that a control is Bound to in code behindWPF:在后面的代码中获取控件绑定到的属性
【发布时间】:2011-02-15 14:09:09
【问题描述】:

我正在尝试找到一种方法来获取控件绑定到的属性(在 c# 中)。

如果我有以下情况:

<dxe:ComboBoxEdit DisplayMember="Name" ItemsSource="{Binding Path=NameOptions, Mode=OneTime}" SelectedItem="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" />

我现在正在尝试获取 SelectedItem 绑定到的位置,即结果应该是“名称”。然后在代码中我需要用那个 ViewModel 属性做一些事情。问题是我不能只是硬编码,因为它是一种通用方法,需要与表单上的每个控件一起使用。

谢谢, 理查德

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    我认为应该这样做:

    BindingExpression be = BindingOperations.GetBindingExpression((FrameworkElement)yourComboBox, ((DependencyProperty)Button.SelectedItemProperty));
    string Name = be.ParentBinding.Path.Path;
    

    To give credit where it's due.

    【讨论】:

    • 感谢您的帮助!完美运行。
    【解决方案2】:

    看看使用BindingExpression

    IE:

    var bindingExpression = this.myComboBox.GetBindingExpression(ComboBox.SelectedItem);
    string bindingPath = bindingExpression.ParentBinding.Path.Path
    

    我看到您使用的是 DXE ComboBox 而不是标准 - 期望它派生自普通的 .NET 控件对象,您应该仍然具有此功能。

    【讨论】:

    • 感谢您的回答,两种方法都试过了,都奏效了。并且在 dxe ComboBox 上运行良好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2020-06-14
    • 2011-02-25
    相关资源
    最近更新 更多