在WPF中绑定一个包含WindowsFormHost项的ItemsControl

3
我正在为我们的WPF应用程序构建一个UI元素,它允许用户以网格格式可视化一组图表。据我了解,您可以使用带有WrapPanel的ItemsControl来很好地对齐UI元素以网格格式显示。
当我们尝试使用winforms图形库(zedgraph)生成图形时,问题就出现了。这意味着我们必须使用WindowsFormsHost来显示图形视图。我已经尝试使用正常数据绑定来绑定图形集合,但它并没有真正起作用:
XAML:
<ItemsControl ItemsSource="{Binding Graphs}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <WindowsFormsHost Margin="5">
                <ui:Graph></ui:Graph>
            </WindowsFormsHost>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

上面的代码没有显示任何内容,但是Graphs getter被访问了。
此外,即使我取消绑定并且只在ItemsControl中插入一些随机图形视图...它仍然不会显示任何内容:
XAML:
<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <WindowsFormsHost Margin="5">
        <ui:Graph></ui:Graph>
    </WindowsFormsHost>
    <WindowsFormsHost Margin="5">
    </WindowsFormsHost>
        <ui:Graph></ui:Graph>
    </WindowsFormsHost>
    <WindowsFormsHost Margin="5">
        <ui:Graph></ui:Graph>
    </WindowsFormsHost>
</ItemsControl>

为了测试图形库的正常功能,确实会显示一个图形:
<Grid>
    <WindowsFormsHost Margin="5">
        <ui:Graph></ui:Graph>
    </WindowsFormsHost>
</Grid> 

有人能引导我正确的方向吗?非常感谢。

我强烈建议创建一个“UserControl”来托管你的WinForms内容,并在此UserControl中创建DependencyProperties,以便您可以获得绑定功能。 - Federico Berasategui
谢谢您的建议。不绑定版本为什么不显示呢?图表在“ItemsControl”之外显示得很好,但在“ItemsControl”内部却无法正常显示。 - Vlad
我猜那可能与布局有关。WinForms非常糟糕,需要硬编码每个元素的大小。尝试为WinFormsHost指定一个固定的WidthHeight值。 - Federico Berasategui
搞定了...为图表设置硬编码大小可行。实际上,绑定也起作用。你应该把它作为答案发布。谢谢! - Vlad
1个回答

2

这可能与布局有关。winforms很糟糕,需要硬编码所有内容的大小。

尝试给winformshost一个固定的硬编码宽度和高度。


已确认此方法也适用于在WrapPanel中使WindowsFormsHost正常工作。但是,在其中托管外部应用程序会出现显示问题 :/ - Scott Solmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接