如何在C#/ WPF(.NET 3.5)中将自定义UserControl
显示为对话框?
答案 0 :(得分:127)
将其放在Window中并致电Window.ShowDialog。
private void Button1_Click(object sender, EventArgs e)
{
Window window = new Window
{
Title = "My User Control Dialog",
Content = new MyUserControl()
};
window.ShowDialog();
}
答案 1 :(得分:10)
Window window = new Window
{
Title = "My User Control Dialog",
Content = new OpenDialog(),
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.NoResize
};
window.ShowDialog();
对我来说就像魔术一样。 它可以作为模态对话框吗?
Ans:ShowDialog它自己将其作为模态对话.. ...
答案 2 :(得分:1)
据我所知你不能这样做。如果你想在对话框中显示它,那就完全没问题,只需创建一个只包含UserControl的新窗口,并在创建该窗口的实例后调用ShowDialog()。
修改强>
UserControl
类不包含ShowDialog方法,因此您尝试做的事实上是不可能的。
然而,这是:
private void Button_Click(object sender, RoutedEventArgs e){
new ContainerWindow().ShowDialog();
}
答案 3 :(得分:1)
namespace System.Window.Form
{
public static class Ext
{
public static DialogResult ShowDialog(this UserControl @this, string title)
{
Window wind = new Window() { Title = title, Content = @this };
return wind.ShowDialog();
}
}
}
使用它可能就像UserControlInstance.ShowDialog()一样简单。 更好的自定义实现是扩展Window类并使用设计器和代码自定义它以获得任何功能。
答案 4 :(得分:0)
我知道这适用于.net 3.5,但这是适用于.net 2.0的解决方案
MyUserControl myUserControl= new MyUserControl();
Form window = new Form
{
Text = "My User Control",
TopLevel = true,
FormBorderStyle = FormBorderStyle.Fixed3D, //Disables user resizing
MaximizeBox = false,
MinimizeBox = false,
ClientSize = myUserControl.Size //size the form to fit the content
};
window.Controls.Add(myUserControl);
myUserControl.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
window.ShowDialog();
答案 5 :(得分:0)
您还可以使用MaterialDesignThemes.Wpf(可从NuGet下载,.NET 4.5+)。然后,您可以简单地执行以下操作:
{
var view = new YourUserControl();
var result = await DialogHost.Show(view, "RootDialog", ClosingEventHandler);
}
private void ClosingEventHandler(object sender, DialogClosingEventArgs eventArgs)
{ } //Handle Closing here
答案 6 :(得分:-1)
如果“sixlettervariables”的答案被修改为如此,则可以正常工作
private void button1_Click ( object sender, RoutedEventArgs e )
{
Window window = new Window
{
Title = "My User Control Dialog",
Content = new UserControl ( ),
Height = 200, // just added to have a smaller control (Window)
Width = 240
};
window.ShowDialog ( );
}