Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Get Property that a control is Bound to in code behind

Tags:

c#

binding

wpf

I am trying to find a way to get the Property to which a control is bound (in c#).

If I have the following:

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

I am now trying to get the location to which the SelectedItem is bound to, i.e. the result should be "Name". Then in code I need to do some stuff with that ViewModel Property. Issue is that I can't just hard code this as it is a generic method that needs to work with each control on the form.

Thanks, Richard

like image 558
Richard Avatar asked May 04 '10 17:05

Richard


2 Answers

I think this should do it:

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

To give credit where it's due.

like image 63
Mark Synowiec Avatar answered Nov 08 '22 12:11

Mark Synowiec


Have a look into using BindingExpression

IE:

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

I see you're using a DXE ComboBox instead of a standard - expecting it derives from a normal .NET control object, you should still have this functionality.

like image 3
Daniel May Avatar answered Nov 08 '22 12:11

Daniel May