• Mvvm KeyDown的实现以及TextBox绑定的属性不更新问题的解决


    今天写程序的时候遇到了个问题:使用mvvm给TextBox在vm层实现KeyDown键盘事件时,TextBox绑定的vm层属性不更新。

    但在TextBox下加个按钮时就更新了。这个问题困扰了我好一会,最后才想起来是更新时机没有给定,所以默认的是LostFocus,故改为PropertyChanged就好了。

     1 <Window x:Class="TestDemo1.MainWindow"
     2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     4         xmlns:cmd="http://www.galasoft.ch/mvvmlight"
     5         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     6         xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
     7         xmlns:ignore="http://www.galasoft.ch/ignore"
     8         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     9         Title="MVVM Light Application"
    10         Width="300"
    11         Height="300"
    12         DataContext="{Binding Main,
    13                               Source={StaticResource Locator}}"
    14         mc:Ignorable="d ignore">
    15 
    16     <Window.Resources>
    17         <ResourceDictionary>
    18             <ResourceDictionary.MergedDictionaries>
    19                 <ResourceDictionary Source="Skins/MainSkin.xaml" />
    20             </ResourceDictionary.MergedDictionaries>
    21         </ResourceDictionary>
    22     </Window.Resources>
    23 
    24     <Grid x:Name="LayoutRoot">
    25         <StackPanel>
    26             <TextBlock Margin="0,50,0,0"
    27                        HorizontalAlignment="Center"
    28                        VerticalAlignment="Center"
    29                        FontWeight="Bold"
    30                        Foreground="Purple"
    31                        Text="{Binding WelcomeTitle}"
    32                        TextWrapping="Wrap" />
    33             <TextBox Margin="20" Text="{Binding MyField, UpdateSourceTrigger=PropertyChanged}">
    34                 <i:Interaction.Triggers>
    35                     <i:EventTrigger EventName="KeyDown">
    36                         <cmd:EventToCommand Command="{Binding MyTestCommand}" />
    37                     </i:EventTrigger>
    38                 </i:Interaction.Triggers>
    39             </TextBox>
    40             <Button Height="20"
    41                     Command="{Binding CmdBtn}"
    42                     Content="Button" />
    43         </StackPanel>
    44     </Grid>
    45 </Window>

     链接:http://files.cnblogs.com/files/zhangyongheng/TestDemo1.rar

  • 相关阅读:
    NOIP2011 D1T1 铺地毯
    NOIP2013 D1T3 货车运输 倍增LCA OR 并查集按秩合并
    POJ 2513 trie树+并查集判断无向图的欧拉路
    599. Minimum Index Sum of Two Lists
    594. Longest Harmonious Subsequence
    575. Distribute Candies
    554. Brick Wall
    535. Encode and Decode TinyURL(rand and srand)
    525. Contiguous Array
    500. Keyboard Row
  • 原文地址:https://www.cnblogs.com/zhangyongheng/p/6510058.html
Copyright © 2020-2023  润新知