2

我有以下

<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}"

指以下(在视图模型中)

public ObservableCollection<PublicationVM> Publications

相同的视图模型暴露

public ICommand DeleteCommand { get; set; }
4

1 回答 1

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

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

public ObservableCollection<PublicationVM> Publications

那么你应该使用RelativeSource你的虚拟机,例如:

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

where UserControl- 你的控件类型 where DataContext= YourViewModel

于 2012-12-06T22:29:43.613 回答