Silverlight中使用DataGrid后,里面的Button的Command不响应的问题

目前这个问题只针对Silverlight得到了解决。原因很简单,因为DataGrid一般在使用的时候都设置了ItemSource,这样里面的Command当然只会响应ItemSource里面的Command方法。这样一来,就需要在页面载入的时候,把页面的ViewModel保存下来,这样就暂时叫DataContext的代理吧,在使用的时候,调这个代理中的Command就可以了。代理可以单独地写成一个类。写法如下:

 1 using System;
2 using System.Windows;
3 using System.Windows.Controls;
4 using System.Windows.Data;
5
6 namespace Common
7 {
8 public class DataContextProxy : FrameworkElement
9 {
10 public DataContextProxy()
11 {
12 this.Loaded += (s, e) =>
13 {
14 Binding binding = new Binding();
15 if (!string.IsNullOrEmpty(BindingPropertyName))
16 {
17 binding.Path = new PropertyPath(BindingPropertyName);
18 }
19 binding.Source = this.DataContext;
20 binding.Mode = BindingMode;
21 this.SetBinding(DataContextProxy.DataSourceProperty, binding);
22 };
23 }
24
25 #region 依赖项属性
26 public Object DataSource
27 {
28 get { return (Object)GetValue(DataSourceProperty); }
29 set { SetValue(DataSourceProperty, value); }
30 }
31
32 public static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof(Object), typeof(DataContextProxy), null);
33
34 public string BindingPropertyName { get; set; }
35 public BindingMode BindingMode { get; set; }
36 #endregion
37 }
38 }


使用的时候需要在Xaml中添加对这个类所在的命名空间进行引用,例如:

xmlns:common="clr-namespace:GoldStock.Common;assembly=GoldStock.Common" 

然后在Xaml中实例化这个代理类,例如:

<UserControl>
<UserControl.Resources>
<common:DataContextProxy x:Key="DataContextProxy"/>
</UserControl.Resources>
</UserControl>

这样在DataGrid中的Button就可以响应命令了。使用如下

<Button Content="修改" Command="{Binding Source={StaticResource DataContextProxy}, Path=DataSource.CommandModify}"/>





原文地址:https://www.cnblogs.com/ca47/p/2354984.html