在开发中遇到实现如下需求的情景:一个输入框,旁边一个清空输入的按钮,当输入框中有内容时显示清空按钮,点击该按钮可以清空输入框内容,当输入框中无内容时隐藏按钮

当然这个需求使用wpf的绑定功能很容易实现

 <TextBox Width="220"
Height="32"
HorizontalAlignment="Right"
HorizontalContentAlignment="Left"
VerticalContentAlignment="Center"
MaxLength="20"
Text="{Binding SearchContent,
UpdateSourceTrigger=PropertyChanged}"
pt:WatermarkHelper.WatermarkContent="{lex:LocText Search}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding TextChangedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<pt:IconLabelButton Width="32"
Margin="-32,0,32,0"
Command="{Binding ClearCommand}"
Icon="/Resource;component/res/GeneralClear.png"
Visibility="{Binding IsShowClearButton,
Converter={StaticResource VisiblityConverter}}" />
   public  ICommand      TextChangedCommand = new DelegateCommand<string>(OnTextChangedCommand);
public ICommand ClearCommand = new DelegateCommand(OnClearCommand); private void OnTextChangedCommand(string obj)
{
if (string.IsNullOrEmpty(SearchContent))
{
IsShowClearButton = false;
return;
} if (SearchContent.Length > )
{
IsShowClearButton = true;
}
else
{
IsShowClearButton = false;
}
} private void OnClearCommand()
{
SearchContent = string.Empty; }

上面思路是通过Textbox的TextChanged事情来处理按钮的显示隐藏。

有没更简单的方案,只在xaml中就实现这个需求,毕竟这个跟业务逻辑完全没关系,只是界面上的变化的东西。

经过努力终于找到方案了,下面看实现方法:需要引用 System.Windows.Interactivity“ 和 ”Microsoft.Expression.Interactions”程序集


<TextBox Width="300" Name="tbSearch"
Height="30"
Style="{DynamicResource TextBoxStyle}"
pt:WatermarkHelper.WatermarkContent="{lex:LocText Search}"
Text="{Binding SearchText}">
</TextBox>
<pt:IconLabelButton Width="32" x:Name="btnClear"
Margin="-32,0,0,0"
Icon="/Resource;component/res/GeneralClear.png">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction TargetObject="{Binding}" PropertyName="SearchText" Value="" />
</i:EventTrigger>
</i:Interaction.Triggers>
<pt:IconLabelButton.Style>
<Style BasedOn="{StaticResource IconLabelButtonStyle}" TargetType="{x:Type pt:IconLabelButton}">
<Style.Triggers>
<DataTrigger Binding="{ Binding ElementName=tbSearch, Path=Text}" Value="">
<Setter Property="Control.Visibility" Value="Hidden" />
</DataTrigger>
</Style.Triggers>
</Style>
</pt:IconLabelButton.Style>
</pt:IconLabelButton>

button控件的显示隐藏通过DataTrigger来实现,通过检测到Textbox的Text属性为空值时,设置属性隐藏。

点击按钮时通过EventTrigger的 ChangePropertyAction   实现, TargetOject绑定到ViewModel, PropertyName设置为TextBox的绑定ViewModel属性,直接改变绑定的属性值实现清空textbox值。

(PS通过ChangePropertyAction 的TargetOject绑定控件, 清空Text属性,可以清空textbox的界面值,但是无法同步textbox的viewmodel绑定值)

只有敢于尝试不同方法才可以进步哟,希望这篇文章对大家有帮助

05-07 15:36