【问题标题】:Dynamically Loading XAML that uses types which have code-behind动态加载使用具有代码隐藏类型的 XAML
【发布时间】:2012-07-10 03:52:29
【问题描述】:

要动态加载的示例 XAML

<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'     
      xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' 
      xmlns:usercontrols='clr-namespace:App.Views.UserControls'>

         <TextBlock>Why don't you click the button?</TextBlock>

         <usercontrols:SuperButton
         Command="{Binding DataContext.OpenURLNew,RelativeSource=
           {RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}}"
         CommandParameter="50">

         ClickMe</usercontrols:SuperButton>
</Grid>

尽管 SuperButton 是在同一个程序集中定义的,但加载失败并显示“无法加载未知类型的用户控件:超级按钮”。

我猜这是因为 SuperButton 有关联的代码隐藏?有没有办法帮助 XamlReader.Load() 找到它需要的东西?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    您所做的应该可以工作 - 尝试在 xmlns:usercontrols='' 中使用完全限定的程序集名称。

    我不久前就做过这件事(也许我写的 netGooey 库可能对你有用)。 netGooey 将 XAML 动态加载到页面中,并支持用户定义的控件。

    我的 XAML 标头如下所示:

    <Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="499" Height="579" xmlns:playback="clr-namespace:inlayShared.ui.controls.playback;assembly=inlayShared" xmlns:library="clr-namespace:inlayShared.ui.controls.library;assembly=inlayShared">

    控件使用如下:

    &lt;playback:volumeSlider Maximum="100" Minimum="0" Margin="42,180,62,0" Height="30" VerticalAlignment="Top" TickFrequency="10" TickPlacement="BottomRight" /&gt;

    动态 XAML 加载如下:

                _gSystem.invokeOnLocalThread((Action)(() =>
                {
                    FileStream fileStream = File.OpenRead(_sUIFile);
                    DependencyObject dependencyObject = XamlReader.Load(fileStream) as DependencyObject;
                    fileStream.Close();
    
                    if (dependencyObject == null)
                        return;
    
                    Content = dependencyObject;
                }), true);`
    

    也许我忘记了让 XAML 注意到自定义控件的一些关键部分,但我很确定它最终会正常工作。

    祝你好运。 (希望完全限定的更改为您修复它)

    http://inlay.codeplex.com/SourceControl/changeset/view/42822#549758

    【讨论】:

    • 成功了!谢谢一堆。赞成并接受。一旦有机会,我会看看你的 netgooey 东西。一段解释你已经建立/试图实现的东西会很方便。据我所知,你现在必须深入研究代码才能弄清楚。
    • 是的。我不再支持那个项目,所以我不会写文档。我提到它主要是因为可能有一些例子说明你应该如何在里面做事。如果您有其他 WPF/动态 XAML 问题,您可以回复此评论并提供指向您的新问题的链接,我会看看。
    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多