Eureka!解决方案是将
HwndSource.SizeToContent
设置为
SizeToContent.WidthAndHeight
。虽然
SizeToContent
与视口能够根据其内容调整大小有关,但这似乎是违反直觉的,但它确实起作用了。我认为它改变了控件重绘的方式。整个解决方案如下:
创建并获取指向WPF用户控件的句柄的函数。 在本例中,名称为
MyControl
:
HWND CChildFrame::GetMyControlHwnd(HWND a_parent, int a_x, int a_y, int a_width, int a_height)
在宿主窗口的OnCreate
中调用GetMyControlHwnd
函数。该函数通过设置HwndSource.ParentWindow
属性自行创建父子关系。
int CChildFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIChildWnd::OnCreate(lpCreateStruct) == -1)
return -1;
m_hMyControl = GetMyControlHwnd(this->GetSafeHwnd(), 0, 0, lpCreateStruct->cx, lpCreateStruct->cy);
return 0;
}
当ChildFrame
调整大小时,我只需更改控件的宽度和高度。
void CChildFrame::OnSize(UINT nType, int cx, int cy)
{
CRect rect;
this->GetWindowRect(&rect);
m_myControl->Width = cx;
m_myControl->Height = cy;
}
我在头文件中有以下私有字段:
// Fields
private:
gcroot<HwndSource^> m_hwndSource;
gcroot<MyControl^> m_myControl;
HWND m_hMyControl;
了解在MFC C++/CLI代码文件中如何包含CLR命名空间很有帮助:
using namespace System;
using namespace System::Windows;
using namespace System::Windows::Interop;