简体   繁体   English

通过单击ListBoxItem将TextBox更改为只读

[英]change TextBox readonly by clicking on ListBoxItem

I have a TextBox inside a ListBoxItem which is disabled so I can drag and drop it in the ListBox . 我在一个禁用的ListBoxItem有一个TextBox ,因此可以将其拖放到ListBox

Once I double click it I want it to be Enabled so I can edit the Text and when I'm done I want it do be Disabled again to do drag and drop. 双击它后,我希望将其Enabled以便编辑Text ,完成后,我希望再次将其Disabled以进行拖放。

I have the MouseDoubleClick event on the ListBoxItem but it doesn't change the TextBox ReadOnly . 我在ListBoxItem上有MouseDoubleClick事件,但它不会更改TextBox ReadOnly Can anybody tell me how to achieve this. 谁能告诉我如何实现这一目标。

at the moment TextBox returns null. 目前, TextBox返回null。 seems like I don't get access to it the way I'm trying. 好像我无法以尝试的方式访问它。

XAML XAML

<ListBox Name="Locations"  Cursor="Hand" HorizontalAlignment="Left" Height="351" Margin="10,48,0,0" VerticalAlignment="Top" Width="285" ItemsSource="{Binding Locations}" dd:DragDrop.IsDragSource="True"
     dd:DragDrop.IsDropTarget="True" SelectedItem="{Binding SelectedItem}">

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
            </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>

In View 视野中

private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
     ListBoxItem item = sender as ListBoxItem;
     textBox.IsReadOnly = false;
}

That's because the textbox "doesn't exists" in the visual tree, WPF creates one for each listitem when needed, so you never have a reference to it. 那是因为文本树在视觉树中“不存在”,WPF在需要时为每个列表项创建一个,因此您永远都没有对它的引用。 It is possible to navigate the visual tree and get the textbox reference but I advise against it, instead, create a property in your item model, something like "EditMode" that when you set it to true, the textbox will enable through the binding of the IsEnabled property. 可以导航视觉树并获取文本框引用,但我建议您不要这样做,而是在项目模型中创建一个属性,例如“ EditMode”,当您将其设置为true时,文本框将通过绑定IsEnabled属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM