2016-11-18 52 views
2

我想訪問我創建的彈出窗口的所有者。如何訪問以編程方式創建Flyout的所有者?

我有代碼:

public void dosomething(Grid lessonGrid) 
{ 
    var invisibleButton = new Button(); 
    lessonGrid.Children.Add(invisibleButton); 

    var contentGrid = new Grid() 

    var buttonInFlyOut = new Button { Content="Click" }; 
    buttonInFlyOut.Click += buttonClicked; 

    contentGrid.Children.Add(buttonInFlyOut); 

    var flyout = new FlyoutForLessons { 
     Content = contentGrid 
    }; 

    flyout.Closed += (f, h) => 
    { 
     lessonGrid.Children.Remove(invisibleButton); 
    }; 

    flyout.Owner = lessonGrid; 
    flyout.ShowAt(invisibleButton); // i want to acces a owner from parent of invisible Button -> lessonGrid 
} 

private class FlyoutForLessons : Flyout 
{ 
    private static readonly DependencyProperty OwnerOfThisFlyOutProperty = DependencyProperty.Register(
     "owner", typeof(UIElement), typeof(FlyoutForLessons), 
     null); 

    public UIElement Owner 
    { 
     get { return (UIElement) GetValue(OwnerOfThisFlyOutProperty); } 
     set { SetValue(OwnerOfThisFlyOutProperty, value); } 
    } 

} 

這段代碼顯示了我一個彈出窗口。所以,當我點擊一個按鈕「buttonInFlyOut」我想「lessonGrid」的ID從發送者在此方法:

private void buttonClicked_Click(object sender, RoutedEventArgs e) 
    { 

    } 

正如你看到的,我試圖創建一個自定義屬性新的彈出按鈕,但我可以」在上面的方法中,從發件人處獲得此彈出窗口。我不知道該怎麼做,我不想創建一個私有的靜態變量來保持網格出現彈出窗口的實例。

如果活立木幫助:

live tree image of flyout

回答

3

沒有理由爲什麼你不能處理點擊事件是這樣的:

public void DoSomething(Grid lessonGrid) 
    { 
     var invisibleButton = new Button(); 
     lessonGrid.Children.Add(invisibleButton); 

     var contentGrid = new Grid(); 

     var buttonInFlyOut = new Button { Content = "Click" }; 
     buttonInFlyOut.Click += (o, args) => 
      { 
       this.OnButtonClicked(lessonGrid); 
      }; 

     contentGrid.Children.Add(buttonInFlyOut); 

     var flyout = new Flyout { Content = contentGrid }; 

     flyout.Closed += (f, h) => { lessonGrid.Children.Remove(invisibleButton); }; 

     flyout.ShowAt(invisibleButton); // i want to acces a owner from parent of invisible Button -> lessonGrid 
    } 

    private void OnButtonClicked(Grid lessonGrid) 
    { 
     // Do something here 
    } 

這使您可以訪問網格,你傳入該方法。

由於Flyout不是FrameworkElement,所以在視覺樹中你永遠不會發現它,這就是爲什麼你看到你的截圖中的彈出窗口在框架之外。如果沒有設置您在方法中訪問的屬性,或者按照上面描述的方式嘗試設置屬性,我認爲不可能這樣做。

+1

哦!謝謝,這就是我剛纔需要的:D 這個問題阻止我走得更遠 解決這個問題非常簡單:) – Niewidzialny

+1

@Niewidzialny這完全沒有問題。我很高興我能幫上忙! –

相關問題