2012-02-01 78 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> 
相關問題