Niewidzialny Niewidzialny - 16 days ago 5
C# Question

How to acces a owner of programmatically created Flyout?

I want to acces a owner of flyout which i created.

I have code:

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

}


This code shows me a flyout. So when i click a button "buttonInFlyOut" i want to get id of "lessonGrid" from sender in this method:

private void buttonClicked_Click(object sender, RoutedEventArgs e)
{

}


As you see, i tried to create a new Flyout with custom property, but i can't get this flyout from sender at method above. I don't know how to do it, and i don't want to create a private static variable which keeps an instance of grid where flyout's appears.

If live tree helps:

live tree image of flyout

Answer

There's no reason why you couldn't handle your click event like this:

    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
    }

This allows you to access the grid that you passed in to the method.

Due to the way that Flyout isn't a FrameworkElement, you'll never find it in the visual tree which is why you see the pop up in your screenshot is outside of the frame. Without either setting a property that you access in your method or trying it in the way I've described above, I don't think it's possible to do this.

Comments