问题描述
我试图在 CS 中实现 XAML。它成功了,但只有一件事我无法解决,那就是: 将其转换为 ContentControl。
object parent = this;
MessageBoxEx.SetParentwindow(this);
必须设置父窗口,否则我会得到一个空引用。
有人可以帮我吗?
找到解决方案
public void InitMessageBox()
{
// Create the ElementHost control for hosting the
// WPF UserControl.
ContentControl host = new ContentControl();
host.DataContext = this;
//host.Dock = DockStyle.Fill;
// Create the WPF UserControl.
MessageBoxEx uc =
new MessageBoxEx();
// Assign the WPF UserControl to the ElementHost control's
// Child property.
//host.Parent = this;
//host.Child = uc;
// Add the ElementHost control to the form's
// collection of child controls.
//this.Controls.Add(host);
// p = (ContentControl) this;
MessageBoxEx.SetParentwindow(host);
MessageBoxEx.SetMessageForeground(Colors.White);
MessageBoxEx.SetMessageBackground(Colors.Black);
MessageBoxEx.SetButtonBackground(MessageBoxEx.ColorFromString("#333333"));
MessageBoxEx.SetButtonTemplateName("AefCustomButton");
MessageBoxEx.SetMaxFormWidth(600);
MessageBoxEx.SetErrorDelegate(new ErrorMsgDelegate());
// if you want to make the MessageBoxEx silent when you use icons,uncomment the next line
//MessageBoxEx.SetAsSilent(true);
}
解决方法
我没有这样做,但您必须遵循特殊的过程才能在 Windows 窗体中使用 WPF 控件。请参阅此链接:Use WPF controls in Windows Forms apps
,我找到了一些代码:
public void InitMessageBox()
{
// Create the ElementHost control for hosting the
// WPF UserControl.
ElementHost host = new ElementHost();
host.Dock = DockStyle.Fill;
// Create the WPF UserControl.
MsgBoxEx.MessageBoxEx uc =
new MsgBoxEx.MessageBoxEx();
// Assign the WPF UserControl to the ElementHost control's
// Child property.
host.Parent = this;
host.Child = uc; // Error
// Add the ElementHost control to the form's
// collection of child controls.
this.Controls.Add(host); // host = error
// p = (ContentControl) this;
MessageBoxEx.SetParentWindow(uc);
MessageBoxEx.SetMessageForeground(Colors.White);
MessageBoxEx.SetMessageBackground(Colors.Black);
MessageBoxEx.SetButtonBackground(MessageBoxEx.ColorFromString("#333333"));
MessageBoxEx.SetButtonTemplateName("AefCustomButton");
MessageBoxEx.SetMaxFormWidth(600);
MessageBoxEx.SetErrorDelegate(new ErrorMsgDelegate());
// if you want to make the MessageBoxEx silent when you use icons,uncomment the next line
//MessageBoxEx.SetAsSilent(true);
}
我从网上得到的这个代码但不起作用