zoukankan      html  css  js  c++  java
  • 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}"/>





  • 相关阅读:
    linux 压力测试工具之ab
    docker save load export import的区别
    手把手教你打造高效的 Kubernetes 命令行终端
    K8S 中的容器编排和应用编排
    linux mount一个目录到另外一个目录
    linux sed命令详解
    各种安全证书间的关系及相关操作
    Linux Shell/Bash wildcard通配符、元字符、转义符使用
    vim打开多个文件、同时显示多个文件、在文件之间切换
    吉他演奏中的速度与节拍
  • 原文地址:https://www.cnblogs.com/ca47/p/2354984.html
Copyright © 2011-2022 走看看