在鼠标双击后启用ListBoxItem中的文本框
本文关键字:文本 ListBoxItem 启用 鼠标 双击 | 更新日期: 2023-09-27 18:04:20
我在ListBoxItem中有一个文本框,它是禁用的,所以我可以把它拖放到ListBox中。
现在我双击它,我希望它是启用的,这样我就可以编辑文本,当我完成后,我希望它再次被禁用,以进行拖放。
我在ListBoxItem上有MouseDoubleClick事件,但我无法访问文本框。有谁能告诉我如何做到这一点吗?
目前在代码隐藏中无法识别textBox。好像我没法用我尝试的方式访问它。
XAML
<ListBox Name="Locations" Cursor="Hand" HorizontalAlignment="Left" Height="351" Margin="10,48,0,0" VerticalAlignment="Top" Width="285" ItemsSource="{Binding Locations}" IsSynchronizedWithCurrentItem="True" dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True" SelectedItem="{Binding SelectedItem}">
<ListBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding DeleteLocationCommand}" />
</ListBox.InputBindings>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
<EventSetter Event="LostFocus" Handler="ListBoxItem_LostFocus"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Name="textBox" Text="{Binding Path=Name}" IsHitTestVisible="False" Width="270" Background="Transparent" BorderThickness="0" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在
private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBoxItem item = sender as ListBoxItem;
textBox.IsReadOnly = false;
Locations.textBox.Background = Brushes.White;
textBox.SelectAll();
Cursor = Cursors.IBeam;
}
private void ListBoxItem_LostFocus(object sender, RoutedEventArgs e)
{
textBox.IsReadOnly = true;
}
你可以使用ReadOnly属性,它将阻止用户对文本进行任何更改:
texBox.ReadOnly = true;
和
private void changeText(object sender, EventArgs e)
{
(sender as TextBox).ReadOnly = false;
}