<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清洁。
<!-- 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 :(得分: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>