将焦点设置在放置在不同UserControl中的文本框中

时间:2018-04-17 11:42:14

标签: c# wpf

我有问题将焦点放在TextBox上,而TextBox放在不同的UserControl中(在我的情况下是CreateLabel UserControl)

<UserControl x:Class="DHL.CreateLabel"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:winforms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
         xmlns:local="clr-namespace:DHL"
         mc:Ignorable="d"
         FocusManager.FocusedElement="{Binding ElementName=dok_idm_textBox}">

<TextBox x:Name="dok_idm_textBox" VerticalAlignment="Top" Margin="15,25,0,0"
                 HorizontalAlignment="Left" Width="200" Height="25" PreviewKeyDown="dok_idm_textBox_PreviewKeyDown"/>

<Grid Grid.Row="2" Margin="25,0,0,0">
            <ScrollViewer VerticalScrollBarVisibility="Hidden">
                <Grid x:Name="Test"></Grid>
            </ScrollViewer>
        </Grid>

...
</UserControl>

我还有DHL_Parcel UserControl,我这样初始化:

 public CreateLabel(ViewModel model)
    {
        InitializeComponent();

        DHL_Parcel parcel = new DHL_Parcel(viewModel);

        Test.Children.Add(parcel);
        Grid.SetColumn(parcel, 0);
        Grid.SetRow(parcel, 2);
    }

问题是:

如何从dok_idm_textBox UserControl设置焦点DHL_Parcel? VisualTree对此有好处吗?

我刚刚找到解决方案:

DependencyObject ucParent = this.Parent;

        while (!(ucParent is UserControl))
        {
            ucParent = LogicalTreeHelper.GetParent(ucParent);

        }
        var test = (CreateLabel)ucParent;
        test.dok_idm_textBox.Text = "";

0 个答案:

没有答案