这是我的场景。我的表格有固定的列数,比如 2,最初,它只有一个可见行,但是当焦点位于第 1 行的最后一列并且用户按下“tab”时,第 2 行将可见。
我的问题是我无法动态选择要使其可见的行,因为我必须在编译期间指定其 x:Name
。
下面是我目前的工作。
.xaml 文件
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" x:Name="SP1">
<TextBox Text="1-1"/>
<TextBox Text="1-2" KeyDown="showNextLine"/>
</StackPanel>
<StackPanel Orientation="Horizontal" x:Name="SP2" Visibility="Collapsed">
<TextBox Text="2-1"/>
<TextBox Text="2-2"/>
</StackPanel>
<!--the remaining rows...-->
</StackPanel>
.cs文件
private int lastRowIndex = 1;
private void showNextLine(object sender, KeyRoutedEventArgs e)
{
lastRowIndex++;
string nextLineName = "SP" + lastRowIndex.ToString();
nextLineName.Visibility = Visibility.Visible; // which causes error because nextLineName is string instead of StackPanel
}
此外,我目前的实现是创建 50 行并使最后 49 行最初不可见,并且我愿意接受任何方法来更系统或更灵活地对所有 TextBox
进行分组。
感谢阅读。
最佳答案
您可以为父 StackPanel 提供一个 x:Name,或者如果您动态创建它,则保留对它的引用:
<StackPanel x:Name="root" Orientation="Vertical">
<StackPanel Orientation="Horizontal" x:Name="SP1">
<TextBox Text="1-1"/>
<TextBox Text="1-2" KeyDown="showNextLine"/>
</StackPanel>
<StackPanel Orientation="Horizontal" x:Name="SP2" Visibility="Collapsed">
<TextBox Text="2-1"/>
<TextBox Text="2-2"/>
</StackPanel>
<!--the remaining rows...-->
</StackPanel>
...然后使用 Children 属性和一些基本的 LINQ 获取对子 StackPanel 的引用:
private void showNextLine(object sender, KeyRoutedEventArgs e)
{
lastRowIndex++;
string nextLineName = "SP" + lastRowIndex.ToString();
StackPanel child = root.Children.OfType<StackPanel>().FirstOrDefault(x => x.Name == nextLineName);
if (child != null)
child.Visibility = Visibility.Visible;
}
How could I create a StackPanel dynamically?
像这样:
var sp = new StackPanel { Name = "SP3", Orientation = Orientation.Horizontal, Visibility = Visibility.Collapsed };
sp.Children.Add(new TextBlock { Text = "3-1" });
var txt = new TextBlock() { Text = "3-2" };
txt.KeyDown += showNextLine;
sp.Children.Add(txt);
root.Children.Add(sp);
关于c# - 在 UWP 应用程序中通过键盘交互修改行的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898458/