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/archive/2012/02/16/2354984.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值