【发布时间】:2013-03-10 06:24:56
【问题描述】:
我正在创建一个由按钮调用的方法。然后该方法将画布添加到按钮的父容器控件。因此,例如,按钮位于网格上。然后该方法创建一个显示在按钮下方的画布。但我有两个问题:
- 如何获取对按钮父容器的引用?
- 是否有容器控件类?我不在乎按钮是否在网格、画布、Stackpanel 等中。所以我正在寻找所有类型的 contianers 实现的接口或它们继承的类。
第二个方面更重要,因为我可以手动传递对容器的引用。
编辑:
它应该看起来像这样(减去颜色,这些只是为了显示不同的元素。
红色画布应该弹出来处理确认。也许甚至有一个漂亮的动画。我的想法是创建一个可以像这样调用的类:
MyPopup popup = new MyPopup("Are you sure?", "Yes", "No", delegateFirstButton, delegateSecondButton);
popup.Show();
到目前为止,我的代码还不是一个类,而只是一个方法。文本部分目前是硬编码的。标记线需要更灵活,这就是我提出问题的原因。
public void ShowPopup(Control senderControl)
{
//I need to have a parameter that accepts all containers instead of this line:
this.myGrid.Children.Add(popup);
Border border = new Border();
popup.Children.Add(border);
border.Margin = new Thickness() { Top = 10 };
border.Child= text;
text.Text = "Are you sure?";
text.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
popup.SizeChanged += delegate { border.Width = popup.ActualWidth; };
popup.Children.Add(btn1);
btn1.Content = "Yes";
btn1.Height = 22;
btn1.Padding = new Thickness(10, 0, 10, 0);
btn1.Margin = new Thickness() { Left = 15, Top = 35 };
popup.Children.Add(btn2);
btn2.Content = "No";
btn2.Height = 22;
btn2.Padding = new Thickness(10, 0, 10, 0);
btn1.SizeChanged += delegate { btn2.Margin = new Thickness() { Left = 30 + btn1.ActualWidth, Top = 35 }; };
popup.Height = 70;
btn2.SizeChanged += delegate
{
popup.Width = 45 + btn1.ActualWidth + btn2.ActualWidth;
updatePositions(senderControl);
};
popup.Background = Brushes.Red;
popup.VerticalAlignment = System.Windows.VerticalAlignment.Top;
popup.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
}
public void updatePositions(Control senderControl)
{
Point location = senderControl.TranslatePoint(new Point(0, 0), this.myGrid);
popup.Margin = new Thickness()
{
Left = location.X + (senderControl.ActualWidth / 2) - (popup.Width / 2),
Top = location.Y + senderControl.ActualHeight + 15
};
}
【问题讨论】:
-
什么??不要在 WPF 的代码中操作 UI 元素。你要那个干什么??我看不出
adds a canvas to the button's parent container control.的原因...请说明您需要什么,我们可以为您提供正确的方法。 -
是的,这正是我想要做的。我用代码在画布上创建了一些元素,需要将它们附加到现有容器。我必须多次展示这个画布并用一行代码调用它。因此,我想将其封装在它自己的方法或类中。
-
I have to show this canvas multiple times... 这可能是DataTemplate或ControlTemplate... 不要在代码中操纵 UI 元素。 WPF 不是 winforms。 -
感谢您的指点。但这并没有真正帮助我......
-
你为什么不使用
Popup类呢?而不是尝试推出自己的
标签: c# wpf containers