简体   繁体   中英

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 .

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.

I have the MouseDoubleClick event on the ListBoxItem but it doesn't change the TextBox ReadOnly . Can anybody tell me how to achieve this.

at the moment TextBox returns null. seems like I don't get access to it the way I'm trying.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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