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>

**我已删除其他设置器属性和资源以保持代码视图清洁。

  • 其次,如何用标签替换按钮并将 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>

先感谢您。:)

问候,

4

2 回答 2

0

似乎 FilterCommand 正在丢失数据上下文,请在定义 FilterCommand 的位置指定 ElementName (例如,将 X:Name 定义为您的窗口并将其作为 Element 提供)

<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>
于 2012-02-01T10:41:12.367 回答
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>

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

于 2012-02-01T09:00:37.213 回答