1

この問題に取り組む方法がよくわかりません:

アクセスキーが添付された「保存」ボタンがあります...しかし、テキストボックスに何かを入力してアクセスキーを押して保存すると、テキストボックスはフォーカスを失うことがないため、ビューモデルを更新しません。UpdateSourceTrigger を PropertyChanged に変更する以外にこれを解決する方法はありますか?

4

1 に答える 1

1

あなたの問題はUpdateSourceTrigger="LostFocus"

これは TextBox のデフォルトであり、TextBox がフォーカスを失ったときにのみバインドされた値を更新することを意味します。

設定せずに強制的に更新する 1 つの方法UpdateSourceTrigger="PropertyChanged"は、KeyPress イベントにフックすることです。キーの組み合わせが保存をトリガーするものである場合は、UpdateSource()最初に呼び出します。

Enter キーでソースを更新する必要がある場合に使用するのが好きな添付プロパティを次に示します。

次のように使用されます。

<TextBox Text="{Binding Name}" 
         local:TextBoxProperties.EnterUpdatesTextSource="True" />

添付プロパティの定義は次のようになります。

public class TextBoxProperties
{
    public static readonly DependencyProperty EnterUpdatesTextSourceProperty =
        DependencyProperty.RegisterAttached("EnterUpdatesTextSource", typeof(bool), typeof(TextBoxProperties), 
            new PropertyMetadata(false, EnterUpdatesTextSourcePropertyChanged));

    // Get
    public static bool GetEnterUpdatesTextSource(DependencyObject obj)
    {
        return (bool)obj.GetValue(EnterUpdatesTextSourceProperty);
    }

    // Set
    public static void SetEnterUpdatesTextSource(DependencyObject obj, bool value)
    {
        obj.SetValue(EnterUpdatesTextSourceProperty, value);
    }

    // Changed Event - Attach PreviewKeyDown handler
    private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var sender = obj as UIElement;
        if (obj != null)
        {
            if ((bool)e.NewValue)
            {
                sender.PreviewKeyDown += OnPreviewKeyDown_UpdateSourceIfEnter;
            }
            else
            {
                sender.PreviewKeyDown -= OnPreviewKeyDown_UpdateSourceIfEnter;
            }
        }
    }

    // If key being pressed is the Enter key, and EnterUpdatesTextSource is set to true, then update source for Text property
    private static void OnPreviewKeyDown_UpdateSourceIfEnter(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            if (GetEnterUpdatesTextSource((DependencyObject)sender))
            {
                var obj = sender as UIElement;
                BindingExpression textBinding = BindingOperations.GetBindingExpression(
                    obj, TextBox.TextProperty);

                if (textBinding != null)
                    textBinding.UpdateSource();
            }
        }
    }
}
于 2011-11-14T18:59:53.603 に答える