我想访问我创建的弹出窗口的所有者。
我有代码:
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)
{
}
如您所见,我尝试使用自定义属性创建一个新的弹出窗口,但我无法通过上述方法从发件人处获取此弹出窗口。我不知道该怎么做,并且我不想创建一个私有(private)静态变量来保留弹出窗口出现的网格实例。
如果活树有帮助:
最佳答案
您没有理由不能像这样处理点击事件:
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,您永远不会在可视化树中找到它,这就是为什么您会看到屏幕截图中的弹出窗口位于框架之外。如果不设置您在方法中访问的属性或按照我上面描述的方式尝试它,我认为不可能做到这一点。
关于c# - 如何访问以编程方式创建的 Flyout 的所有者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685449/