问题遇到的现象和发生背景
WPF中MVVM模式中,有的情况下某些元素的Command有时候Binding无效,比如Hyperlink或Button,附上整个测试工程!
Window中有三个控件,两个ListBox,一个Button。主要的测试目的是:想通过样式来统一Listbox的元素布局,并且每个元素中可以有自己的事件;
然后也创建了ListBoxItem的样式Style;
该Style中有一个Image,一个Textbox(用于修改内容来测试),一个Button;
问题相关代码
样式的代码
<Window.Resources >
<Style TargetType="{x:Type ListBoxItem}" x:Key="listItem">
<Setter Property="FontSize" Value="18"></Setter>
<Setter Property="Content" Value="{Binding Content, Mode=TwoWay}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border BorderThickness="10">
<StackPanel>
<Image Source="./Resource/mask.png" Stretch="None"></Image>
<TextBox VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding Content,Mode=TwoWay}"></TextBox>
<!--这里的命令绑定无效是怎么回事呢?-->
<Button Command="{Binding TextChangedCommand}" CommandParameter="123" >
Command of bingding can not work
</Button>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemContainerStyle" Value="{StaticResource listItem}"></Setter>
</Style>
</Window.Resources>
布局应用的代码
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Name="listbox1" >
</ListBox>
<ListBox Grid.Row="1" Name="listbox2">
</ListBox>
<Button FontSize="18" Grid.Row="2" Command="{Binding TextChangedCommand}" CommandParameter="123"> Command of bingding work </Button>
</Grid>
运行结果及报错内容
Style样式中的Button无法绑定Command,而布局中直接定义的Button则可以,这是为什么呢?
我想要达到的结果
想要每个Button都可以绑定Command
[](链接:https://pan.baidu.com/s/1FGMoGNcQcV-CpO78nlJaEQ
提取码:1010)