2012-02-01 77 views
0
  • 从下面看到的DataTemplate,我已经创建了按钮的列表视图。我为此按钮指定了Command和CommandParameter。但是,当这些按钮是CanExecute和Execute方法不会被触发。现在,如果我在用户控件上放置一个按钮并绑定命令,事件就会触发。为什么会发生?
 <ListView ItemContainerStyle="{StaticResource AlphabetsContainerStyle}" 
       ItemsSource="{Binding Alphabets}"/> 
      <Button Command="{Binding Path=FilterCommand}" CommandParameter="A"/> <!-- Works --> 


      <!-- Code in the Resource Dictionary File --> 

      <DataTemplate x:Key="AlphabetsTemplate"> 
        <Border>    
         <Button Content="{Binding}" 
           Command="{Binding Path=FilterCommand}" 
           CommandParameter="A"/>     <!-- Doesn't Work --> 
        </Border> 
      </DataTemplate> 

      <Style TargetType="{x:Type ListBoxItem}" x:Key="AlphabetsContainerStyle"> 
       <Setter Property="ContentTemplate" Value="{StaticResource AlphabetsTemplate}"/> 
      </Style> 

** 我已删除了其他setter属性和资源保持代码查看干净。绑定式ListBoxItem与RelayCommand

  • 其次,我该如何用标签替换按钮并将ICommand直接附加到ListBoxItem?
<!-- Replacing Button with Label --> 
<DataTemplate x:Key="AlphabetsTemplate"> 
      <Border>    
       <Label Content="{Binding}"   <!-- Label Doesnt have Command Property --> 
      </Border> 
    </DataTemplate> 

<!-- How can I set Command directly to ListBoxItem ?--> 
    <Style TargetType="{x:Type ListBoxItem}" x:Key="AlphabetsContainerStyle"> 
     <Setter Property="ContentTemplate" Value="{StaticResource AlphabetsTemplate}"/> 
    </Style> 

预先感谢您。 :)

问候,

回答

0

对于Button情况下,你应该改变风格的秩序和DataTemplate-

<DataTemplate x:Key="AlphabetsTemplate"> 
     <Border>    
      <Button Content="{Binding}" 
        Command="{Binding Path=FilterCommand}" 
        CommandParameter="A"/>     <!-- Doesn't Work --> 
     </Border> 
</DataTemplate>  

<Style TargetType="{x:Type ListBoxItem}" x:Key="AlphabetsContainerStyle"> 
    <Setter Property="ContentTemplate" Value="{StaticResource AlphabetsTemplate}"/> 
</Style> 

对于标签,请注明您的要求。

+0

如您所描述的顺序是一样的,但我在这里以等级顺序呈现以便更好地理解。我正在改变它以避免误解。 – Marshal 2012-02-01 09:24:04

0

似乎FilterCommand正在失去的datacontext,FilterCommand已经被定义,其中指定的ElementName(如定义X:命名你的窗口,将它作为元)

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" x:Name="A1"> 
    <Window.Resources> 

     <DataTemplate x:Key="AlphabetsTemplate"> 
      <Border> 
       <Button Content="{Binding}" 
         Command="{Binding Path=FilterCommand, ElementName=A1}" 
         CommandParameter="A"/>    
      </Border> 
     </DataTemplate> 
相关问题