我用按钮创建了DataGridTemplateColumn
。我用Command
绑定了它,但在点击它之后,没有任何反应。但是,如果我将按钮移动到DataGrid的Outside,它可以正常工作。
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding MedCards}">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding = "{Binding Id, Mode=TwoWay}"/>
<DataGridTextColumn Header="ID клиента" Binding = "{Binding Client_Id, Mode = TwoWay}"/>
<DataGridTextColumn Header="Вес" Binding = "{Binding Weight, Mode = TwoWay}"/>
<!-- <DataGridTextColumn Header="Рекомендация" Binding = "{Binding Recommend, Mode = TwoWay}"/> -->
<DataGridTemplateColumn Header="Рекомендация">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=ShowRecommendCommand}" CommandParameter="{Binding Recommend}" Content="Посмотреть"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- -->
<DataGridTextColumn Header="Рост" Binding = "{Binding Height, Mode = TwoWay}"/>
<DataGridTextColumn Header = "Проблемы" Binding = "{Binding Problems, Mode = TwoWay}"/>
<DataGridTextColumn Header = "BodyType" Binding = "{Binding BodyType, Mode = TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
命令:
private RelayCommand showRecommendCommand;
public RelayCommand ShowRecommendCommand
{
get
{
return showRecommendCommand ??
(showRecommendCommand = new RelayCommand(obj =>
{
RecommendViewModel viewModel = new RecommendViewModel();
viewModel.Recommend = Convert.ToString(obj);
RecommendWindow window = new RecommendWindow();
window.Show();
}));
}
}
答案 0 :(得分:-1)
您的Button
位于DataTemplate
内,因此无法直接访问外部数据上下文。试试这个。
为您的DataGrid
命名
<DataGrid Name="myGrid" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding MedCards}">
然后使用ElementName
来访问绑定中的外部数据上下文。
<Button Command="{Binding Path=DataContext.ShowRecommendCommand, ElementName=myGrid}" CommandParameter="{Binding Recommend}" Content="Посмотреть"/>
另外,为了将来参考,请在调试时打开立即窗口以查看绑定错误。