Finding the Bound property, from a UIElement, after it has been bound
Case:
开发者_StackOverflowpublic class customer
{
public string Adress { get; set; }
}
Xaml:
<Grid x:Name="LayoutRoot" Background="White" > <StackPanel> <TextBox Text="{Binding Adress}"/> </StackPanel> </Grid>
.cs
public MainPage() { InitializeComponent(); LayoutRoot.DataContext = new customer() { Adress = "Some Adr" }; }
So the Question is, in code behind. how do I get the property (string) of the bound (Adress). I need it to access the customer.adress as a property, to assign another variable. (in this case when a event occours. e.g. after the this.Loaded occurs.)
So I got the UIElement
(sender) and I can get the customer form its DataContext
.
In short, how do I get the property name of the binding object. (the binding object is easy to find I just use DataContext
to get the customer, but where can I get the name of the property? that are in the xaml (eg. name) from the sender)
(I plan to use reflection if it is nessesery to access the "adress" inside customer) but how to get the "name" of the property that text in the textBox is bound to.
Try the following:
Give your TextBox
a name, so you can access it from code:
<Grid>
<TextBox Name="textBox" Text="{Binding Adress}" />
</Grid>
In code behind:
BindingExpression bExpr = textBox.GetBindingExpression(TextBox.TextProperty);
The name of the bound property can now be extracted as a string from:
bExpr.ParentBinding.Path.Path
However, I would advise against this; try to use established MVVM principles and find out the bound values in the view-models instead of from the views. If you state your problem a bit more clearly, like for instance, if there are multiple customers in a list and you need the address of the selected one, we might be able to help further.
精彩评论