从DataTemplate单​​击事件

时间:2016-08-09 11:51:57

标签: c# wpf xaml

我已将命令绑定到按钮上。按钮上的CanExecute方法被调用,但单击该按钮不会导致调用Execute方法。

这是xaml代码

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:Invoices.HelloWorldRoutedCommand}"
                    Executed="OnExecute"
                    CanExecute="OnCanExecute"  />
</Window.CommandBindings>
<Window.Resources>
    <DataTemplate x:Key="ItemTemplate" >
        <WrapPanel >
           <Button x:Name="ImageBtn" 
                   Background="Red" 
                Command="{x:Static    local:Invoices.HelloWorldRoutedCommand}">
                <StackPanel >
                    <Image Width="70" Height="55" 
                          Source="{Binding img}"  />
                    <TextBlock Text="{Binding text}"         VerticalAlignment="Center" 
HorizontalAlignment="Center" FontFamily="GE Flow" />
                </StackPanel>

            </Button>
        </WrapPanel>
    </DataTemplate>
</Window.Resources>
<Grid x:Name="Product_grid" Grid.Column="1">
        <ListView  Name="listView" 
          ItemTemplate="{StaticResource ItemTemplate}" >
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="5"  />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
        <TextBlock Name="ProductName"
           Text=""
           DataContext="{StaticResource ItemTemplate}" />
</Grid>

代码隐藏

public partial class Invoices : Window
{
  public static RoutedCommand HelloWorldRoutedCommand = new RoutedCommand();
  public void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
   {
     e.CanExecute = true;
   }
  public void OnExecute(object sender, ExecutedRoutedEventArgs e)
   {
      MessageBox.Show("test");
   }
}

0 个答案:

没有答案