相关疑难解决方法(0)

9
推荐指数
2
解决办法
8076
查看次数

当打开Window时,如何将一个datatemplated TextBox聚焦在Window中ItemsControl的第一个元素中?(C#,WPF)

当用户单击应用程序中的按钮时,会打开一个窗口.我想要将属于ItemsControl中第一项的TextBox聚焦,这样用户可以在打开Window时立即开始输入,而无需手动选择TextBox.

如何才能做到这一点?

为简单起见,我们可以说Window看起来大致如下:

<Window>
    <Grid>
        <ItemsControl ItemsSource="{Binding MyItems}">
            <DataTemplate>
                <Grid>
                    <StackPanel>
                        <StackPanel>
                            <customControls:ValidationControl>
                                <TextBox Text="" />
                            </customControls:ValidationControl>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ItemsControl>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

更新后查看提出的答案以及此链接: Window Loaded和WPF 修改后的解决方案如下:

<Window>
    <Grid>
        <ItemsControl x:Name="myItemsControl" ItemsSource="{Binding MyItems}">
            <DataTemplate>
                <Grid>
                    <StackPanel>
                        <StackPanel>
                            <customControls:ValidationControl>
                                <TextBox Text="" />
                            </customControls:ValidationControl>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ItemsControl>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

在构造函数中:

this.Loaded += new RoutedEventHandler(ThisWindowLoaded);
Run Code Online (Sandbox Code Playgroud)

加载方法:

private void ThisWindowLoaded(object sender, RoutedEventArgs e)
{
    var textbox = FindVisualChild<TextBox>(myItemsControl.ItemContainerGenerator.ContainerFromIndex(0));
    FocusManager.SetFocusedElement(myItemsControl, textbox);
}
Run Code Online (Sandbox Code Playgroud)

超级方法:

public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject …
Run Code Online (Sandbox Code Playgroud)

c# wpf textbox focus itemscontrol

4
推荐指数
1
解决办法
1664
查看次数

如何将UserControl中的所有文本框添加到GridView中

在页面上,我将UserControl动态添加到GridView中。因此,每个UserControl可以包含不同类型的控件(TextBox,CheckBox,单选按钮)

例如,UserControl的名称是:UserForm。

问题:如何使用VisualTreeHelper获取控件集合并检查textBox是否为空。

我找到了与该问题类似的代码,并对其进行了修改,但无法正常工作。

我不知道这意味着什么,是否需要?

list.AddRange(AllTextBoxes(child))

我应该使用MyList.Select()还是MyList.Where()吗?

无效的FindTextBoxes()
{

   列表<TextBox> MyList = AllTextBoxes(UserForm);

   var count = MyList.Where(x => if(string.IsEmptyOrNull(x.Text));

}




列出<TextBox> AllTextBoxes(DependencyObject父对象)
{
    var list = new List <TextBox>();

    为(int i = 0; i <VisualTreeHelper.GetChildrenCount(parent); i ++)
    {
        var child = VisualTreeHelper.GetChild(parent,i);

        如果(子项是TextBox)

            list.Add(子级为TextBox);

        list.AddRange(AllTextBoxes(child));
    }
    返回清单;
}


winrt-xaml

2
推荐指数
1
解决办法
792
查看次数