我有一个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;