2

これは私のChildWindowxamlコードです:

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>

これは私のUserControl1xamlコードです:

1     <Grid x:Name="LayoutRoot" Background="#FFA34444">
2      <Button Click="Child_Close" Content="Cancel">
3     </Grid>

これは私のUserControlC#です:

private void Child_Close(object sender, System.Windows.RoutedEventArgs e)
{
 ChildWindow cw = (ChildWindow)this.Parent;
 cw.Close();
}

この方法を試してみても機能しません。何か案が?

Tks Josi

4

2 に答える 2

4

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();

これにより、たまたま 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 に答える