datagrid列按钮命令(MVVM)

时间:2012-12-06 14:54:35

标签: silverlight mvvm datagrid

我有以下

<ResourceDictionary 

xmlns:vm="clr-namespace:SilverlightApplication1.ViewModels.Controls"> 

<DataTemplate DataType="vm:CVItemVM" x:Key="viewmodel">

..........

                    <sdk:DataGrid Grid.Row="1" AutoGenerateColumns="False" Width="820" MaxColumnWidth="395" ItemsSource="{Binding Path=Publications}" Visibility="{Binding Path=Publications.Count, Converter={StaticResource ConverterVisibility2_1}}">
                        <sdk:DataGrid.ColumnHeaderStyle>
                            <Style TargetType="sdk:DataGridColumnHeader">
                                <Setter Property="FontWeight" Value="Bold" />                                     
                            </Style>
                        </sdk:DataGrid.ColumnHeaderStyle>
                        <sdk:DataGrid.Columns>
                            <sdk:DataGridTextColumn Header="Title" Binding="{Binding Path=Title}"  CanUserResize="False" IsReadOnly="True" />
                            <sdk:DataGridTextColumn Header="Author" Binding="{Binding Path=Author}" CanUserResize="False" IsReadOnly="True"  />
                            <sdk:DataGridTemplateColumn Header="">                                    
                                <sdk:DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <Button Content="{Binding Path=Id}" Command="{Binding Path=DeleteCommand, Mode=TwoWay}" />                                            
                                    </DataTemplate>
                                </sdk:DataGridTemplateColumn.CellTemplate>
                            </sdk:DataGridTemplateColumn>                                
                        </sdk:DataGrid.Columns>
                    </sdk:DataGrid>

我面临的问题是

<Button Content="{Binding Path=Id}" Command="{Binding Path=DeleteCommand, Mode=TwoWay}" />                                            

不会触发绑定到的命令。

ItemsSource="{Binding Path=Publications}"

指的是以下(在viewmodel中)

public ObservableCollection<PublicationVM> Publications

相同的viewmodel公开

public ICommand DeleteCommand { get; set; }

1 个答案:

答案 0 :(得分:7)

<Button Content="{Binding Path=Id}" Command="{Binding Path=DeleteCommand, Mode=TwoWay}" />

此代码尝试从PublicationVM对象访问DeleteCommand属性。如果在那里定义了这样的属性,它应该工作(如果属性不是null ofc。)。 如果DeleteCommand在同一个VM中定义

public ObservableCollection<PublicationVM> Publications

然后你应该使用RelativeSource到您的VM,例如:

<Button Content="{Binding Path=Id}" Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" />

其中UserControl - 您的控件类型DataContext = YourViewModel