Get other property in class of bound property
If I got a nested class that I am binding to, how could I retrieve that parent class. For example, I have bound to SecondClass.ImageSource. I now want to get the information of the SecondClass when I click on the Image,开发者_高级运维 how can I achieve this?
I would like to change the SecondClass property, but the problem is that I have a grid of the same image items.
The binding of the image works already.
Xaml:
<Image Source="{Binding Path=SecondClass.ImageSource}" Width="48" Height="48" MouseUp="Image_MouseUp_1" />
Code:
public class FirstClass {
public int number { get; set; }
public SecondClass SecondClass
}
public class SecondClass {
public ImageSource ImageSource { get; set; }
}
private void Image_MouseUp_1(object sender, MouseButtonEventArgs e) {
FirstClass item = ????
}
You can only bind to SecondClass.ImageSource
because the DataContext
of the Image
is an instance of FirstClass
. So in the handler you only need to cast it:
private void Image_MouseUp_1(object sender, MouseButtonEventArgs e) {
FirstClass item = (sender as Image).DataContext as FirstClass;
//<Change item.SecondClass or do whatever you want>
}
Your Data Object either needs to know it's parent object, or you can use a RelativeSource
or ElementName
binding to reference a parent object. For example
<Window x:Name="RootWindow" DataContext="{Binding FirstClass}">
<Grid DataContext="{Binding SecondClass.SomeProperty}">
<!-- Binding using ElementName -->
<Button Context="{Binding ElementName=RootWindow,
Path=DataContext.SecondClass}" />
<!-- Binding using RelativeSource -->
<Button Context="{Binding RelativeSource=
{RelativeSource AncestorType={x:Type Window}},
Path=DataContext.SecondClass}" />
</Grid>
</Window>
精彩评论