shitangmai 2022-05-16 17:34 采纳率: 0%
浏览 9
已结题

WPF中MVVM模式中,有的情况下某些元素的Command有时候Binding无效,比如Hyperlink或Button,附上整个测试工程

问题遇到的现象和发生背景

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)

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 5月24日
    • 创建了问题 5月16日

    悬赏问题

    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线