私はTextBox
とPopup
コントロールを持っています。Popup.IsOpen
プロパティをプロパティにバインドしたいTextBox.IsFocused
。つまり、テキスト ボックスにフォーカスがある場合、ポップアップが開いています。または、ポップアップにフォーカスがある場合、テキストボックスがフォーカスを失ったためにポップアップを閉じたくありません。イベントハンドラーでこれを処理するのではなく、バインディングを使用してこれを処理することを望んでいました。また、依存関係プロパティは既存のもの (つまり、登録、メタデータのオーバーライドなど) であるため、依存関係プロパティに関して何かを行う必要がありますか、またはこれらのプロパティにバインドするだけでよいでしょうか。
これが私のシナリオに似たサンプルコードです
StackPanel sp = new StackPanel();
TextBox tb = new TextBox();
Popup popup = new Popup();
sp.Children.Add(tb);
sp.Children.Add(popup);
this.Content = sp;
Binding bd = new Binding("IsFocused");
bd.source = tb.IsFocused;
popup.SetBinding(Popup.IsOpenProperty, bd);
このことから、テキスト ボックス コントロールをクリックしてフォーカスを与えるとポップアップが開き、逆にテキスト ボックスがフォーカスを失うとポップアップが閉じると想定していました。私はこれを機能させることができないようです。
誰かが私が間違っていることを知っている場合、テキストボックスがフォーカスを失ったがフォーカスを受け取ったのはポップアップだった場合、ポップアップが開いたままになるか、フォーカスを戻すという私の質問の後半にも答えることができるかもしれません最初のバインディングの前に開いたままになるように、テキストボックスに追加します。テキスト ボックスがフォーカスを失ったときにフォーカスを取得するその他のコントロールは、このシナリオには適用されません。
わかりやすくするためにこれを言い換えることができるとしたら、私はこのように言います。
1.)バインドPopup.IsOpen
するTextBox.IsFocused
2.)にバインドTextBox.IsFocused
しPopup.IsFocused
ます (これにより、フォーカスがテキスト ボックスに戻されると仮定します) 。
これが私の最初のC#の試みです。何かがまだ正しくありません。何も起こらないので、どこが間違っているのかよくわかりません。
StackPanel sp = new StackPanel();
TextBox tb = new TextBox();
Popup popup = new Popup();
TextBox popupTextBox = new TextBox();
popup.Child = popupTextBox;
sp.Children.Add(tb);
sp.Children.Add(popup);
this.Content = sp;
//***Questions concerning giving the UIElement a name and registering it
tb.Name = "siblingTextBox";
System.Windows.NameScope.GetNameScope(tb).RegisterName("siblingTextBox", tb);
//***Questions concerning giving the UIElement a name and registering it
popupTextBox.Name = "popupTextBox";
System.Windows.NameScope.GetNameScope(tb).RegisterName("popupTextBox", popupTextBox);
Binding binding = new Binding();
binding.ElementName = tb.Name;
popup.PlacementTarget = tb;
Style style = new Style();
style.TargetType = typeof(Popup);
DataTrigger dataTrigger = new DataTrigger();
Binding focusedBinding = new Binding("IsFocused");
focusedBinding.ElementName = tb.Name;
dataTrigger.Value = true;
dataTrigger.Binding = focusedBinding;
Setter setter = new Setter();
setter.Property = Popup.IsOpenProperty;
setter.Value = true;
dataTrigger.Setters.Add(setter);
style.Triggers.Add(dataTrigger);
dataTrigger = new DataTrigger();
focusedBinding = new Binding("IsFocused");
focusedBinding.ElementName = popupTextBox.Name;
dataTrigger.Value = true;
dataTrigger.Binding = focusedBinding;
setter = new Setter();
setter.Property = Popup.IsOpenProperty;
setter.Value = true;
dataTrigger.Setters.Add(setter);
style.Triggers.Add(dataTrigger);
popup.Style = style;