wpfeventstelerikradtreeviewcustom-button

How to pass current node object to to command in telerik RadtreeviewItem in wpf


I'm using Kendo Telerik RadTreeview control in WPF.. I have functionality that for each RadTreeViewItem node I'm adding a custom button which on command event show pop up.

I have added button and used it in HierarchicalDataTemplate as below

<HierarchicalDataTemplate x:Key="BuildingStructure"
                              ItemsSource="{Binding Levels, Mode=TwoWay}"
                              ItemContainerStyle="{StaticResource levelNodeStyle}">
        <Grid HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition  Width="3*"/>
                <ColumnDefinition  Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" 
                       Width="250"
                       Text="{Binding StructureName , Mode=TwoWay}" 
                       HorizontalAlignment="Left"
                       Panel.ZIndex="2"/>
            <Button
                Canvas.Left="10" 
                Canvas.Bottom="20"
                Panel.ZIndex="1"
                BorderThickness="0"
                BorderBrush="Transparent"
                Background="Transparent"
                 Foreground="White"
                HorizontalAlignment="Left"
                Grid.Column="1"
                VerticalAlignment="Stretch"
                Command="{Binding DataContext.AddLevelRadTreeCommand, RelativeSource={RelativeSource AncestorType=telerik:RadTreeView}}" 
                CommandParameter="{Binding ElementName=radTreeView}"
                Margin="0 2 0 5">

                <Image
                    Width="20"
                    Height="20"
                   Source="/Project;component/Resources/Images/03-Add.png"/>
            </Button>
        </Grid>


    </HierarchicalDataTemplate>

What I want is that on command event i need to add command parameter that will pass the current RadTreeviewItem data object which is assign to that node like below

StructId:1,
StructName:'Building A'....and so on...

Solution

  • When you template out data into controls, the datacontext of the control becomes the viewmodel you're templating. Each of whatever in Levels becomes the datacontext of the treewview item produced.

    DataContext is inherited down the visual tree.

    Hence the datacontext of the button is the treeviewitem's.

    Where you have

     CommandParameter="{Binding ElementName=radTreeView}"
    

    You want the datacontext the button is in. Which should be something like:

    CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Self}}"
    

    Thinking about it a little more, it could also be

    CommandParameter="{Binding}"