mayur rathi mayur rathi - 1 year ago 114
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

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" >
<Grid x:Name="LayoutGrid">
<ColumnDefinition Width="*" />
<ColumnDefinition Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualHeight}" />
<TextBlock Text="{Binding someproperty}" Grid.Column="0">
<Button x:Name="btn1" ">
<Image Source="someImage.png"/>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="Commands:MyCommand" >
<MultiBinding Converter="{Converters:MyConverter}">
<Binding />
<Binding Source="{RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}}" />

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 Source

You're binding should be as follows:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download