Binding LinkButton in datagrid with Command Using MVVM


  • I have following xaml code.

     <sdk:DataGrid  AutoGenerateColumns="False" ItemsSource="{Binding StudentList, Mode=TwoWay}">
                        <sdk:DataGridTextColumn Binding="{Binding Path=RollNumber}" Header="Roll Number" IsReadOnly="True"  />
                        <sdk:DataGridTextColumn Binding="{Binding StudentName}" Header="Student Name" IsReadOnly="True"/>
                        <sdk:DataGridTextColumn Binding="{Binding DateOfBirth, Converter={StaticResource showOnlyDate}}" Header="Date Of Birth" IsReadOnly="True"/>
                        <sdk:DataGridTextColumn Binding="{Binding RecordAge}" Header="Created Since" IsReadOnly="True"/>
                        <sdk:DataGridTextColumn Binding="{Binding RecordOwner}" Header="Created By" IsReadOnly="True"/>
                                    <HyperlinkButton Content="Delete"  Margin="5,2" Foreground="Black" ToolTipService.ToolTip="{Binding StudentName, StringFormat='Delete {0}'}"
                                                         Command="{Binding  Path=DataContext.Delete,ElementName=HomePage}" CommandParameter="Some Value"/>


    In the above code you can see that I have set the ItemSource for the datagrid and bind each of the property which is in the collection. But I have one command which need to bi bind with the delete linkbutton in the data grid. the command didn't fire when I click on the delete linkbutton in the grid. what is wrong with the code. 


    Wednesday, June 01, 2011 1:26 AM


  • Hi Asim

    I cant say why, but Element to element binding sometimes does not work in certain scenerios.

    But if you declare your ViewModel as a StaticResource in your Usercontrol resources and bind your Hyperlink button as:

    <HyperlinkButton Content="Delete"  Margin="5,2" Foreground="Black" ToolTipService.ToolTip="{Binding StudentName, StringFormat='Delete {0}'}"
                                                         Command="{Binding  Delete, Source={StaticResource ViewModel}}/>

    Then it would surely work.

    If the ViewModel constructor takes some Parameters then you can add the ViewModel as a StsticResource in your xaml.cs file like this:

    Resources.Add("ViewModel", viewModel);

    This should be done before the InitializeComponent() method.

    Wednesday, June 01, 2011 1:53 AM