【问题标题】:How to acces a owner of programmatically created Flyout?如何访问以编程方式创建 Flyout 的所有者?
【发布时间】:2016-11-19 19:13:03
【问题描述】:

我想访问我创建的浮出控件的所有者。

我有代码:

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)
   {

   }

如您所见,我尝试使用自定义属性创建一个新的 Flyout,但我无法通过上述方法从发件人那里获取此 Flyout。我不知道该怎么做,并且我不想创建一个私有静态变量来保留一个出现浮出控件的网格实例。

如果活树有帮助:

【问题讨论】:

    标签: c# uwp


    【解决方案1】:

    你没有理由不能像这样处理你的点击事件:

        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 的方式,您永远不会在可视化树中找到它,这就是为什么您会在屏幕截图中看到弹出窗口位于框架之外的原因。如果没有设置您在方法中访问的属性或按照我上面描述的方式尝试它,我认为不可能做到这一点。

    【讨论】:

    • 哦!谢谢,这正是我所需要的 :D 这个问题阻止了我进一步解决这个问题的方法很简单 :)
    • @Niewidzialny 完全没问题。我很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多