WPF学习笔记(二):初学者避坑实录

使用 KeyBinding 实现文本框回车提交

文本框的回车提交是一个很常见的需求:在一个复杂的筛选页面上,用户希望在输入框输入文字后直接回车即可触发查询,而不是非得点击一下搜索按钮。假设需要在用户输入回车时触发 TestCommand 命令,则对应的实现代码如下:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding TestCommand}" Key="Return"></KeyBinding>
    </TextBox.InputBindings>
</TextBox>

属性优先级问题导致的 DataTrigger 不生效

这是一个新手特别容易犯的一个错误。

在下面的代码中我希望实现的效果是:一个文本框,如果用户未输入任何内容则展示边框,一旦用户有输入,则将边框隐藏。

<TextBox BorderThickness="0" x:Name="TestTextBox">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Text.Length,ElementName=TestTextBox}" Value="0">
                    <Setter Property="BorderThickness" Value="1" />
                </DataTrigger>
            </Style.Triggers>
</Style>
    </TextBox.Style>
</TextBox>

但程序运行后结果并不符合预期:边框一直没有出现。

这个问题的出现是因为 BorderThickness 被直接定义在了有更高优先级的 TextBox 标签上,该操作覆盖了 DataTrigger 的行为。

问题的解决方式也很简单:将 BorderThickness 的设置移入 Style 标签即可。

<TextBox  x:Name="TestTextBox">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Setter Property="BorderThickness" Value="0" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Text.Length,ElementName=TestTextBox}" Value="0">
                    <Setter Property="BorderThickness" Value="1" />
                </DataTrigger>
            </Style.Triggers>
</Style>
    </TextBox.Style>
</TextBox>

图片源为空时展示默认图片

列表中展示缩略图也是很常见的需求。在信息管理系统中,不能保证所有信息都包含缩略图。在没有包含特定缩略图时,需要展示默认缩略图。

<Image>
    <Image.Source>
        <Binding Path="ImageUri" >
            <Binding.TargetNullValue>
                <ImageSource>/Assets/PlaceHolder.png</ImageSource>
            </Binding.TargetNullValue>
        </Binding>
    </Image.Source>
</Image>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值