如何UserControl
在C#/ WPF(.NET 3.5)中将自定义显示为对话框?
如何UserControl
在C#/ WPF(.NET 3.5)中将自定义显示为对话框?
Answers:
将其放在窗口中,然后调用Window.ShowDialog。(此外,如果尚未添加对以下内容的引用:PresentationCore,WindowsBase和PresentationFramework。)
private void Button1_Click(object sender, EventArgs e)
{
Window window = new Window
{
Title = "My User Control Dialog",
Content = new MyUserControl()
};
window.ShowDialog();
}
this.Close()
在此UserControl对话框中使用功能?
Owner = Application.Current.MainWindow
Window window = new Window
{
Title = "My User Control Dialog",
Content = new OpenDialog(),
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.NoResize
};
window.ShowDialog();
对我来说就像魔术一样。可以将其作为模式对话框吗?
回答:ShowDialog它使自己成为模态对话框.. ...
据我所知你不能那样做。如果要在对话框中显示它,那很好,只需创建一个仅包含UserControl的新Window,然后在创建该Window的实例后调用ShowDialog()。
编辑:
本UserControl
类不包含的方法ShowDialog的,所以你想做什么,其实是不可能的。
但是,这是:
private void Button_Click(object sender, RoutedEventArgs e){
new ContainerWindow().ShowDialog();
}
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类并使用设计器和代码对其进行自定义以获取任何功能。
我知道这适用于.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();
您还可以使用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
如果对“ 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 ( );
}
Background = Brushes.Purple
; 没有它就行不通。