6

XAML とデータ バインディング (MVVM) を使用します。ユーザーが TextBox に新しいテキスト文字を書き込むときに、Label を更新する必要があります。

XAML

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="463" Text="{Binding OriginalText}"/>
        <Label Height="28" HorizontalAlignment="Left" Margin="12,41,0,0" Name="label1" VerticalAlignment="Top" Width="463" Content="{Binding ModifiedText}"/>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="400,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

ビューモデル

    class MainViewModel : NotifyPropertyChangedBase
    {
        private string _originalText = string.Empty;
        public string OriginalText
        {
            get { return _originalText; }
            set
            {
                _originalText = value;
                NotifyPropertyChanged("OriginalText");
                NotifyPropertyChanged("ModifiedText");
            }
        }

        public string ModifiedText
        {
            get { return _originalText.ToUpper(); }
        }
    }

XAML にボタンを追加しました。ボタンは何もしませんが、テキストボックスのフォーカスを失うのを助けます。フォーカスを失うと、バインディングが更新され、上部のテキストがラベルに表示されます。ただし、データ バインディングは、テキストがフォーカスを失ったときにのみ更新されます。TextChanged イベントはバインディングを更新しません。TextChanged イベントで強制的に更新したいと思います。どうやってやるの?どのコンポーネントを使用すればよいですか?

4

1 に答える 1

15
 <TextBox Name="textBox1"
      Height="23" Width="463"
      HorizontalAlignment="Left" 
      Margin="12,12,0,0"   
      VerticalAlignment="Top"
      Text="{Binding OriginalText, UpdateSourceTrigger=PropertyChanged}" /> 

MSDN の方法: TextBox テキストがソースを更新するタイミングを制御する:

プロパティのTextBox.TextデフォルトのUpdateSourceTrigger値は LostFocusです。これは、データ バインドされた TextBox.Text プロパティを持つ TextBox がアプリケーションにある場合、TextBox に入力したテキストは、TextBox がフォーカスを失うまで (たとえば、TextBox から離れた場所をクリックしたとき)、ソースを更新しないことを意味します。

入力中にソースを更新する場合は、バインディングの UpdateSourceTrigger をPropertyChangedに設定します。次の例では、TextBox と TextBlock の両方の Text プロパティが同じソース プロパティにバインドされています。TextBox バインディングの UpdateSourceTrigger プロパティが PropertyChanged に設定されています。

于 2012-07-17T12:29:26.057 に答える