我需要帮助才能访问例如。来自代码的TextBox。我使用VB但C#示例也很受欢迎。 如果我尝试通过键入txtSettingsCity来访问TextBox,则VB无法识别TextBox。
我非常感激。提前谢谢。
<Button x:Name="btnSettings" FontSize="16" FontFamily="Segoe MDL2 Assets" Content="" Foreground="{StaticResource NuhmeTextColor}" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignBottomWithPanel="True" Margin="4,0,0,4">
<Button.Flyout>
<MenuFlyout x:Name="mfSettings">
<MenuFlyoutItem x:Name="mfiSettings">
<MenuFlyoutItem.Template>
<ControlTemplate TargetType="MenuFlyoutItem">
<StackPanel Margin="4,10,4,0" Orientation="Vertical" Width="130">
<TextBox x:Name="txtSettingsCity" Header="Din placering" PlaceholderText="Ribe, Danmark" Width="130" Margin="0,0,0,10" ToolTipService.ToolTip="Indtast din placering eller klik søg"/>
<Button x:Name="btnFindLocation" Content="Søg" Margin="80,0,0,10" Click="btnFindLocation_Click"/>
</StackPanel>
</ControlTemplate>
</MenuFlyoutItem.Template>
</MenuFlyoutItem>
</MenuFlyout>
</Button.Flyout>
</Button>
答案 0 :(得分:0)
您可以循环浏览VisualTreeHelper.GetParent以首先获取父MenuFlyoutItem,然后递归使用VisualTreeHelper.GetChild返回TextBox。
但是,我强烈建议您探索MVVM方法并将Button.Command绑定到ICommand并将TextBox绑定作为Button.CommandParameter传递。
快速而肮脏的例子
private void btnFindLocation_OnClick(object sender, RoutedEventArgs e)
{
var target = sender as DependencyObject;
while (target != null)
{
target = VisualTreeHelper.GetParent(target);
if (target is MenuFlyoutItem menuFlyoutItem)
{
if (GetChild<TextBox>(menuFlyoutItem) is TextBox textBox)
{
// Access the TextBox here
Debug.WriteLine(textBox.Text);
}
}
}
}
private TFrameworkElement GetChild<TFrameworkElement>(FrameworkElement parent) where TFrameworkElement : FrameworkElement
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (var index = 0; index < count; ++index)
{
var child = VisualTreeHelper.GetChild(parent, index) as FrameworkElement;
if (child is TFrameworkElement frameworkElement)
{
return frameworkElement;
}
else
{
if (GetChild<TFrameworkElement>(child) is TFrameworkElement grandChild)
{
return grandChild;
}
}
}
return null;
}
答案 1 :(得分:0)
为什么不使用VisualTreeHelprer
,这是一个快速的代码示例;
Public Shared Function FindParent(Of T As DependencyObject)(ByVal child As DependencyObject) As T
Dim parentObject As DependencyObject = VisualTreeHelper.GetParent(child)
If parentObject Is Nothing Then Return Nothing
Dim parent As T = TryCast(parentObject, T)
If parent IsNot Nothing Then Return parent Else Return FindParent(Of T)(parentObject)
End Function
该功能的用法:
Dim parent As ControlTypeHere= FindParent(Of ControlTypeHere)(Me)