您的位置:首页 > 其它

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

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

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Common
{
public class DataContextProxy : FrameworkElement
{
public DataContextProxy()
{
this.Loaded += (s, e) =>
{
Binding binding = new Binding();
if (!string.IsNullOrEmpty(BindingPropertyName))
{
binding.Path = new PropertyPath(BindingPropertyName);
}
binding.Source = this.DataContext;
binding.Mode = BindingMode;
this.SetBinding(DataContextProxy.DataSourceProperty, binding);
};
}

#region 依赖项属性
public Object DataSource
{
get { return (Object)GetValue(DataSourceProperty); }
set { SetValue(DataSourceProperty, value); }
}

public static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof(Object), typeof(DataContextProxy), null);

public string BindingPropertyName { get; set; }
public BindingMode BindingMode { get; set; }
#endregion
}
}


使用的时候需要在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}"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐