Silverlight中使用MVVM(7):DataGrid中触发Button的Click事件

简介: 转自http://www.cnblogs.com/626498301/archive/2012/02/02/2335439.html  Silverlight中使用MVVM(1)--基础 Silverlight中使用MVVM(2)—提高 ...

转自http://www.cnblogs.com/626498301/archive/2012/02/02/2335439.html

 

Silverlight中使用MVVM(1)--基础

Silverlight中使用MVVM(2)—提高

Silverlight中使用MVVM(3)—进阶

Silverlight中使用MVVM(4)—演练

Silverlight中使用MVVM(5)-Command II

Silverlight中使用MVVM(6):AutoComplteBox的异步过滤

毕业后忽然觉得什么地方都要用钱, 这半年除了工作上,业余时间做了些小活,因此没有什么时间静下心来分享一些东西了,生活压力山大啊.

这篇文章分享MVVM中常见的一个问题,相信在实际运用MVVM的朋友一定会遇到这种问题.

   <sdk:DataGridTemplateColumn Header="功能"  Width="Auto">
     <sdk:DataGridTemplateColumn.CellTemplate>
         <DataTemplate >
             <StackPanel Orientation="Horizontal">
                 <Button Content="删除" Margin="10,0" Command="{Binding ShowCommand}"  Height="24" 
                        HorizontalAlignment="Left" VerticalAlignment="Center" >
                 </Button>
             </StackPanel>
         </DataTemplate>
     </sdk:DataGridTemplateColumn.CellTemplate>
  </sdk:DataGridTemplateColumn>

在CellTemplate中的Button与ViewModel中的Command属性绑定时.你会发现Button无法触发这个事件

如何处理这种情况呢,我的做法是这样的:

   public class DataContextProxy:TriggerAction<DependencyObject>
  {
      protected override void Invoke(object parameter)
      {
          var parent = this.AssociatedObject as DependencyObject;
          var fe = this.AssociatedObject as FrameworkElement;
          while (parent != null)
          {
              if (parent.GetType() == typeof(DataGrid))
              {
                  var context = parent as DataGrid;
                  fe.DataContext = context.DataContext;
                  break;
              }
              parent = VisualTreeHelper.GetParent(parent) as DependencyObject;
          }
 
      }
  }

继承一个TriggerAction,具体的原理就不叙述了,Button引用这个TriggerAction ,不要忘了System.Windows.Interactivity这个dll噢^^

      <Button Content="删除" Margin="10,0" Command="{Binding ShowCommand}"  Height="24" 
            HorizontalAlignment="Left" VerticalAlignment="Center" >
              <i:Interaction.Triggers>
                  <i:EventTrigger>
                      <local:DataContextProxy/>
                  </i:EventTrigger>
              </i:Interaction.Triggers>
      </Button>

这样就可以了.另外一种方式可以参考:stackOverFlow.如何取舍就由各位自己分析比较吧.

示例下载:DataGridWithButton.rar

目录
相关文章

热门文章

最新文章