在wpf的datagrid中使用<DataTemplate>
标签来放一列button,出现了无法绑定command的问题
简单的Command=”{Binding AddCommand}”不行
下面是解决办法
<DataGridTemplateColumn Header="opt" Width="120" MaxWidth="120" CanUserReorder="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="buy" Command="{Binding DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=DataGrid}}" Click="buy_click" >
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
关键在于
Command="{Binding DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=DataGrid}}"
此外,有时我们需要多个viewModel,解决怎么把不同的xaml文件和ViewModel绑定起来花了不少时间
下面是解决方案
<Window
.............
xmlns:VM="clr-namespace:Citi.Training.WPF.ViewModel"
.................
<Window.DataContext>
<VM:MyBondsWindowViewModel />
</Window.DataContext>
..............
<Grid>
.................
</Grid>
namespace要换成viewModel所在的namespace