silverlight - 为什么 XamlReader.Load 无法识别 Silverlight 4 中的附加属性?

标签 silverlight xaml silverlight-4.0 resourcedictionary attached-properties

我试图弄清楚如何在我们的 Silverlight 4 应用程序中以编程方式在运行时应用主题。我认为这应该像从 XAML 加载资源字典并将其与应用程序的合并字典合并一样简单。到目前为止,这是我的代码:

var themeUri = new Uri(
    "OurApp;component/Themes/Classic/Theme.xaml", UriKind.Relative);
var resourceInfo = GetResourceStream(themeUri);
using (var stream = resourceInfo.Stream)
{
    using (var reader = new StreamReader(stream))
    {
        var xamlText = reader.ReadToEnd();
        var dict = XamlReader.Load(xamlText) as ResourceDictionary;
        Resources.MergedDictionaries.Add(dict);
    }
}

不幸的是,一个 XamlParseException在调用 XamlReader.Load 期间引发:

The attachable property 'Foo' was not found in type 'Bar'.



此正确附加已正确声明,并且 XAML 中的命名空间声明正确引用了所需的命名空间。如果通过 App.xaml 标记以声明方式加载到合并的字典中,附加属性 XAML 就可以正常工作。

这是我尝试在运行时加载的 XAML 的缩写副本:
<ResourceDictionary xmlns:u="clr-namespace:Company.Product.Utils"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Style x:Key="ControlPanelStyle" TargetType="ContentControl">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ContentControl">
          <Grid Margin="0" u:Bar.Foo="True">
            <!-- Stuff and things -->
            <ContentPresenter Content="{TemplateBinding Content}" />
          </Grid>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>

为什么在运行时加载 XAML 时对附加属性的引用不起作用,而在“静态”加载时它工作得很好?

最佳答案

我只是想出了问题的根源。在我们的 XAML 中,我们声明了我们的命名空间,如下所示:

xmlns:u="clr-namespace:Company.Product.Utils"

似乎虽然这适用于静态编译的 XAML,但它不适用于动态加载的 XAML,因为在动态加载时,命名空间的程序集不会得到解析。一旦我们将命名空间声明更改为这个,它就起作用了:
xmlns:u="clr-namespace:Company.Product.Utils;assembly=OurAssembly"

关于silverlight - 为什么 XamlReader.Load 无法识别 Silverlight 4 中的附加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754697/

相关文章:

c# - 从 MVVM 中的 DataGrid 或 ListBox 绑定(bind)到 SelectedItems

Silverlight 工具包 - 带主题的 ChildWindow

silverlight - 如何在 ListBox 中的 DataTemplate 中获取 TextBox 以通知 ViewModel 值更改

c# - 关闭/删除选项卡项 WPF

c# - Xamarin.Forms:IValueConverter 只工作一次

silverlight - Silverlight 4 浏览器外应用程序可以运行其他应用程序吗?

mvvm - wcf ria服务中的调用操作无法包含外键表

银光 4 : Reliable Commanding with RequerySuggested Functionality?

c# - 数据网格上工具提示的 silverlight 4 图像预览

Silverlight - 史诗般的图形失败(由两个三角形组成的矩形):(