使用 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>