这是我的 ChildWindow xaml 代码:
1 <Grid x:Name="LayoutRoot">
2 <Grid x:Name="teste">
3 <Grid.ColumnDefinitions>
4 <ColumnDefinition Width="*"/>
5 <ColumnDefinition Width="*"/>
6 </Grid.ColumnDefinitions>
7 <Grid.RowDefinitions>
8 <RowDefinition />
9 <RowDefinition Height="Auto" />
10 </Grid.RowDefinitions>
11 <local:UserControl1 Grid.Row="0" Grid.ColumnSpan="2"/>
12 </Grid>
13 </Grid>
这是我的 UserControl1 xaml 代码:
1 <Grid x:Name="LayoutRoot" Background="#FFA34444">
2 <Button Click="Child_Close" Content="Cancel">
3 </Grid>
这是我的用户控件 C#:
private void Child_Close(object sender, System.Windows.RoutedEventArgs e)
{
ChildWindow cw = (ChildWindow)this.Parent;
cw.Close();
}
尝试这种方法是行不通的。
任何想法?
Tks
Josi
UserControl 的父级的问题不是ChildWindow
,它是子窗口内的 Grid。你需要得到的父母的父母UserControl
导航至ChildWindow
:-
ChildWindow cw = (ChildWindow)((FrameworkElement)this.Parent).Parent;
然而,将其嵌入到您的UserControl
这是不好的做法,你会向你的消费者规定UserControl
它可以放置在哪里。在上述情况下,要使用户控件正常工作,它需要始终是布局根的直接子级。
更好的方法是搜索视觉树来寻找ChildWindow
。我会使用这个辅助方法(实际上我会将其放在辅助扩展静态类中,但我会在这里保持简单)。
private IEnumerable<DependencyObject> Ancestors()
{
DependencyObject current = VisualTreeHelper.GetParent(this);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
现在您可以使用 LINQ 方法来获取 ChildWindow:-
ChildWindow cw = Ancestors().OfType<ChildWindow>().FirstOrDefault();
这将找到您的 UserControl 的第一个祖先,它恰好是 ChildWindow。这允许您的 UserControl 放置在子窗口 XAML 中的任何深度,它仍然会找到正确的对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)