2015-08-22 23 views
1

我已经创建了一个简单的测试解决方案来测试数据模板中的按钮并将其设置为ContentControl。然而,在目前的实施中没有工作和回应。按钮命令不能在DataTemplate中工作

MainWindow.xam

<Window x:Class="ButtonCommandWithDataTemplate.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:ux="clr-namespace:ButtonCommandWithDataTemplate" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources> 
    <ResourceDictionary> 
     <DataTemplate x:Key="SimpleView" DataType="{x:Type ux:InnerViewModel}"> 
      <Button Command="{Binding ClickCommand}" Content="Click" /> 
     </DataTemplate> 
    </ResourceDictionary> 
</Window.Resources> 
<Grid> 
    <ContentControl > 
     <ContentControl.Style> 
      <Style TargetType="{x:Type ContentControl}"> 
       <Setter Property="ContentTemplate" Value="{StaticResource SimpleView}" /> 
      </Style> 
     </ContentControl.Style> 
    </ContentControl> 
</Grid> 

MainWindowViewModel.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Input; 

namespace ButtonCommandWithDataTemplate 
{ 
    public class MainWindowViewModel 
    { 
     private InnerViewModel innerVm; 

     public InnerViewModel InnerVm 
     { 
      get { return innerVm; } 
      set { innerVm = value; } 
     } 

     public MainWindowViewModel() 
     { 
      this.innerVm = new InnerViewModel(); 
     } 
    } 
} 

InnerViewModel.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Input; 

namespace ButtonCommandWithDataTemplate 
{ 
    public class InnerViewModel 
    { 
     private ICommand clickCommand; 

     public ICommand ClickCommand 
     { 
      get 
      { 
       if (this.clickCommand == null) 
       { 
        this.clickCommand = new RelayCommand(param => 
        { 
         try 
         { 
          MessageBox.Show("W0w"); 
         } 
         catch (Exception exception) 
         { 
          throw exception; 
         } 
        }); 
       } 

       return this.clickCommand; 
      } 
     } 
    } 
} 

Download project

回答

1

在你的项目,我下载了你有这个

<DataTemplate x:Key="SimpleView"> 
      <Button Command="{Binding Path=DataContext.ClickCommand, 
      RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
      Content="Click" /> 
</DataTemplate> 

我改成了这一点,它为我工作

<DataTemplate x:Key="SimpleView"> 
      <Button Command="{Binding Path=DataContext.InnerVm.ClickCommand, 
      RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
      Content="Click" /> 
</DataTemplate> 

DataContext的是MainViewModel它没有一个点击指令,它在InnerViewModel上。

+0

感谢您的指导! – user1219310