Accessing TextBox inside a ContextMenu

≯℡__Kan透↙ 提交于 2020-01-05 08:13:56

问题


I've got a TextBox that's part of a ContextMenu's MenuItem. However, I can't seem to access that TextBox the same way I can access other controls that are outside of the ContextMenu. Here's my XAML:

    <ListBox Name="ItemList">
        <ListBox.Resources>
            <ContextMenu x:Key="listBoxItemContextMenu">
                <MenuItem Header="Rename">
                    <TextBox Name="newFilename" KeyUp="renameFile" />
                </MenuItem>
            </ContextMenu>
        </ListBox.Resources>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="ContextMenu" Value="{StaticResource listBoxItemContextMenu}"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

The TextBox I'm trying to access is 'renameFile'.


回答1:


Try this code

ContextMenu cm = ItemList.Resources["listBoxItemContextMenu"] as ContextMenu;
MenuItem mi = cm.Items[0] as MenuItem;
TextBox tb = mi.Items[0] as TextBox;


来源:https://stackoverflow.com/questions/7049057/accessing-textbox-inside-a-contextmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!