2

这是我的 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 乔西

4

2 回答 2

4

UserControl 的父级的问题不是ChildWindowGrid,而是子窗口内的 Grid。您需要让父级的父级UserControl导航到ChildWindow:-

ChildWindow cw = (ChildWindow)((FrameworkElement)this.Parent).Parent;

但是,将其嵌入到您的UserControl不良做法中,您将向您的消费者规定UserControl它可以放置在哪里。在上述情况下,要使用户控件正常工作,它必须始终是 Layout 根的直接子级。

更好的方法是搜索视觉树寻找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();

这将找到恰好是 ChildWindow 的 UserControl 的第一个祖先。这允许将您的 UserControl 放置在子窗口 XAML 中的任何深度,它仍然会找到正确的对象。

于 2009-11-26T15:57:31.653 回答
0

这是我当前的(临时)解决方案 - 一个ChildPopupWindowHelper静态类来打开弹出窗口,而不必为我想要公开的每个用户控件创建一个愚蠢的 ChildWindow XAML 实例。

  • 像往常一样创建用户控件,继承自ChildWindowUserControl

  • 然后打开一个弹出窗口

    ChildPopupWindowHelper.ShowChildWindow("TITLE", new EditFooControl())

我对此并不完全满意,并欢迎对此模式进行改进。


public static class ChildPopupWindowHelper
{
    public static void ShowChildWindow(string title, ChildWindowUserControl userControl)
    {
        ChildWindow cw = new ChildWindow()
        {
            Title = title
        };
        cw.Content = userControl;
        cw.Show();
    }
}

public class ChildWindowUserControl : UserControl
{
    public void ClosePopup()
    {
        DependencyObject current = this;
        while (current != null)
        {
            if (current is ChildWindow)
            {
                (current as ChildWindow).Close();
            }

            current = VisualTreeHelper.GetParent(current);
        }
    }
}
于 2010-07-15T01:08:57.853 回答