WPF---Xaml中改变ViewModel的值
在開發(fā)中遇到實(shí)現(xiàn)如下需求的情景:一個(gè)輸入框,旁邊一個(gè)清空輸入的按鈕,當(dāng)輸入框中有內(nèi)容時(shí)顯示清空按鈕,點(diǎn)擊該按鈕可以清空輸入框內(nèi)容,當(dāng)輸入框中無內(nèi)容時(shí)隱藏按鈕
?
當(dāng)然這個(gè)需求使用wpf的綁定功能很容易實(shí)現(xiàn)
<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中就實(shí)現(xiàn)這個(gè)需求,畢竟這個(gè)跟業(yè)務(wù)邏輯完全沒關(guān)系,只是界面上的變化的東西。
經(jīng)過努力終于找到方案了,下面看實(shí)現(xiàn)方法:需要引用?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來實(shí)現(xiàn),通過檢測(cè)到Textbox的Text屬性為空值時(shí),設(shè)置屬性隱藏。
點(diǎn)擊按鈕時(shí)通過EventTrigger的?ChangePropertyAction ? 實(shí)現(xiàn), TargetOject綁定到ViewModel, PropertyName設(shè)置為TextBox的綁定ViewModel屬性,直接改變綁定的屬性值實(shí)現(xiàn)清空textbox值。
(PS通過ChangePropertyAction 的TargetOject綁定控件, 清空Text屬性,可以清空textbox的界面值,但是無法同步textbox的viewmodel綁定值)
?
?
? ? ? ?只有敢于嘗試不同方法才可以進(jìn)步喲,希望這篇文章對(duì)大家有幫助
?
轉(zhuǎn)載于:https://www.cnblogs.com/karl-F/p/7267174.html
總結(jié)
以上是生活随笔為你收集整理的WPF---Xaml中改变ViewModel的值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Quick Search Article
- 下一篇: 设计模式------中介者模式