使用RelayCommand绑定样式ListBoxItem

时间:2012-02-01 08:20:57

标签: c# wpf xaml mvvm icommand

  • 从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属性和资源,以保持codeview清洁。

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

提前谢谢你。 :)

此致

2 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分: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>