mayur rathi mayur rathi - 2 months ago 16
C# Question

How to get the object of parent usecontrol in wpf

I have created a user control lets say UserControl1. I have a child control button, by clicking on which I want to pass the object of the UserControl1 and the data bound with the button to the converter. I am using MVVM pattern for command execution.

Lets say the Xaml file for User Control is structured as below

<local:UserControl1 x:Class="UserControl1
xmlns:Converters="clr-namespace:MyConverter"
xmlns:......>


somewhere in the Xaml there is a Listbox containing the ListItem and a button for doing some action on the ListBox as represented below

<ListBox x:Name="SomeViewmodel" MinWidth="300" MaxWidth="300" Height ="Auto" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="LayoutGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualHeight}" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding someproperty}" Grid.Column="0">
</TextBlock>
<Border
<Button x:Name="btn1" ">
<Image Source="someImage.png"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="Commands:MyCommand" >
<i:InvokeCommandAction.CommandParameter>
<MultiBinding Converter="{Converters:MyConverter}">
<Binding />
<Binding Source="{RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}}" />
</MultiBinding>
</i:InvokeCommandAction.CommandParameter>
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>




I am able to send the object to the converter but the object recieved at converter is of type System.Windows.Data.RelativeSource where as it should be UserControl1.

What am I missing? or what should I do to get the UserControl1 Object from RelativeSourceObject ?

Answer

You're binding should be as follows:

<MultiBinding Converter="{Converters:MyConverter}">
    <Binding />
    <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}}"  />
</MultiBinding>

i.e. The binding should use the RelativeSource property, not the Source property.