我有一个显示文本框列表的WPF ListBox。当我点击文本框时,ListBox的选择不会改变。我必须在文本框旁边单击才能选择ListBox项。是否需要设置某个属性使文本框将点击事件转发到ListBox?
我有一个显示文本框列表的WPF ListBox。当我点击文本框时,ListBox的选择不会改变。我必须在文本框旁边单击才能选择ListBox项。是否需要设置某个属性使文本框将点击事件转发到ListBox?
基于Arcturus Answer的附加行为,使其可重用且不会隐藏在代码后面。
public static class SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior
{
public static readonly DependencyProperty EnableProperty = DependencyProperty.RegisterAttached(
"Enable",
typeof(bool),
typeof(SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior),
new FrameworkPropertyMetadata(false, OnEnableChanged));
public static bool GetEnable(FrameworkElement frameworkElement)
{
return (bool)frameworkElement.GetValue(EnableProperty);
}
public static void SetEnable(FrameworkElement frameworkElement, bool value)
{
frameworkElement.SetValue(EnableProperty, value);
}
private static void OnEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ( d is ListBoxItem listBoxItem)
listBoxItem.PreviewGotKeyboardFocus += ListBoxItem_PreviewGotKeyboardFocus;
}
private static void ListBoxItem_PreviewGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
var listBoxItem = (ListBoxItem)sender;
listBoxItem.IsSelected = true;
}
}
例如<Windows.Resources>
<Window.Resources>
<Style TargetType="ListViewItem">
<Setter Property="myBehavior:SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior.Enable" Value="true"/>
</Style>
</Window.Resources>
如果Visual Studio没有自动添加命名空间,例如当您的项目名为"MyApp"并且您将文件保存在"MyBehaviors"文件夹中时,命名空间将位于Window下:
<Window
xmlns:myBehavior="clr-namespace:MyApp.MyBehaviors"
>
尝试这段代码:
foreach (object item in this.listBox1.Items) {
if (textbox1.text.equals(item.toString())) {
//show error message; break
}
}
我不确定您是否想要像先前的答案中描述的那样直接设置选择,因为我认为这会破坏多选和其他一些情况。
您可以尝试像下面这样重新设计按钮,看看会发生什么。
<Button ClickMode="Pressed" Focusable="False">
<Button.Template>
<ControlTemplate> // change the template to get rid of all the default chrome
<Border Background="Transparent"> // Button won't be clickable without some kind of background set
<ContentPresenter />
</Border>
</ControlTemplate>
</Button.Template>
<TextBox />
关于您的初始情况,您没有提供很具体的信息。但我假设您使用了DataBinding和ItemTemplate。我认为这是一个简单的方法,尤其是对于初学者来说。以下是代码:
<ListBox ItemsSource="{Binding someDataCollection}" Name="myListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding datafield}" Tag="{Binding .}"
GotFocus="TextBox_GotFocus"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
myListBox.SelectedItem = (sender as TextBox).Tag; /* Maybe you need to cast to the type of the objects contained in the collection(bound as ItemSource above) */
}
Listbox处理项目选择,但不知道嵌入其中的文本框的焦点。如果您想在文本框获得输入焦点时更改选择,则需要手动更改列表框选择,据我所知。