我在 Windows 8.1 C# 应用程序中尝试了以下操作:
<!-- XAML file -->
<Page.BottomAppBar>
<CommandBar>
<AppBarButton Label="Add News Feed" Icon="Add">
<AppBarButton.Flyout>
<Flyout>
<StackPanel Width="400">
<TextBlock TextWrapping="Wrap" Text="Enter Text:" Margin="0,0,0,10"/>
<TextBox x:Name="inputTextBox"/>
<Button Content="Add" HorizontalAlignment="Right" VerticalAlignment="Stretch" Click="AddButton_Click"/>
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
// C# file
private void AddButon_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var text = inputTextBox.Text;
// Do something with the text
}
但是,当我运行我的应用程序并单击添加按钮时,我得到一个 System.NullReferenceException,因为成员 inputTextBox 为空。我检查并生成的 InitializeComponent 方法具有以下行:
inputTextBox = (global::Windows.UI.Xaml.Controls.TextBox)this.FindName("inputTextBox");
我什至尝试将我的事件处理程序更改为调用 FindName,以防在显示 Flyout 时创建控件并且它仍然返回 null。为什么 FindName 找不到我的文本框?
更新:解决方法
我能够使用 VisualTreeHelper 访问 TextBox,如下所示:
TextBox textBox = null;
var parent = VisualTreeHelper.GetParent(sender as Button);
var numChildren = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < numChildren; ++i)
{
var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (child != null && child.Name == "inputTextBox")
{
// Found the text box!
textBox = child as TextBox;
break;
}
}
if (textBox != null)
{
var text = textBox.Text;
// Do something with the text
}
如果这确实被确认为 Windows 8.1 预览版中的错误,我将继续解决这个问题。