ユーザーコントロール内にテキストボックスがあります。Usercoptrol には、String 型の Dependency プロパティ "Text" があります。ユーザーコントロールの Text プロパティは、TextBoxes Text プロパティにバインドされています。
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(String),
typeof(MyTextControl),
new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
xaml コード...
<TextBox
x:Name="textbox1"
Text="{Binding ElementName=MyTextControl, Path=Text, UpdateSourceTrigger=LostFocus}"
...
</TextBox>
注意してください私たちのアプリには、「元に戻す」機能を提供するために、UpdateSourceTrigger が PropertyChanged ではなく LostFocus であるという理由があります。テキストを変更すると、フォーカスが失われたときに元に戻すステップが作成されます。
ユーザーが Usercontrol の外側で、アプリ内の別のコントロールをクリックした場合があります。「FocusLost」イベントは、wpf システムによって起動されません。したがって、私は
Mouse.PreviewMouseDownOutsideCapturedElement
このような場合の更新に役立つことがわかりました。
このイベントをキャッチするには、テキストが変更されたときにマウス キャプチャを設定し、クリックが発生したときにキャプチャを解放する必要があります。
private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
Mouse.Capture(sender as IInputElement);
}
private void OnPreviewMouseDownOutsideCapturedElement(object sender, MouseButtonEventArgs args)
{
var result= VisualTreeHelper.HitTest(this, args.GetPosition(this));
if (result!= null)
{
// clicked inside of usercontrol, can keep capture, no work!
}
else
{
// outside of usercontrol, now store the text!
if (_textbox != null)
{
_textbox.ReleaseMouseCapture();
// do other text formatting stuff
// assign the usercontrols dependency property by the current text
Text = _textbox.Text;
}
}
}
このメカニズムが実装されていて、ユーザーがテキスト ボックスのどこかをクリックすると、他の UIElement の PreviewGotKeyboardFocus などのトンネリング イベントがキャプチャのために発生しないことがわかりました。
private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
// never gets called!
Debug.WriteLine(" OnPreviewGotKeyboardFocus");
}
このメカニズムが他のクリックされた要素の PreviewGotKeyboardFocus イベントをブロックしないようにするにはどうすればよいですか?