WPF---Xaml中改变ViewModel的值
在開發中遇到實現如下需求的情景:一個輸入框,旁邊一個清空輸入的按鈕,當輸入框中有內容時顯示清空按鈕,點擊該按鈕可以清空輸入框內容,當輸入框中無內容時隱藏按鈕
?
當然這個需求使用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 > 0){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綁定值)
?
?
? ? ? ?只有敢于嘗試不同方法才可以進步喲,希望這篇文章對大家有幫助
?
轉載于:https://www.cnblogs.com/karl-F/p/7267174.html
總結
以上是生活随笔為你收集整理的WPF---Xaml中改变ViewModel的值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Quick Search Article
- 下一篇: 【转】ROWNUM与ORDER BY先后