C# 资源和内容控制模板

C# 资源和内容控制模板,c#,wpf,C#,Wpf,在代码隐藏中将contentcontrols模板设置为xaml时,我无法访问父xaml中包含的静态资源 我有一个contentcontrol,如下所示: <ContentControl x:Name="ccMaterial"> <ContentControl.Resources> <x:Array x:Key="BondListKey" Type="sys:Int32" xmlns:sys="clr-namespace:Sys

在代码隐藏中将contentcontrols模板设置为xaml时,我无法访问父xaml中包含的静态资源

我有一个contentcontrol,如下所示:

<ContentControl x:Name="ccMaterial">
  <ContentControl.Resources>
    <x:Array x:Key="BondListKey" Type="sys:Int32" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib" />
  </ContentControl.Resources> 
</ContentControl>
   string template = "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
     "<ComboBox Grid.Column=\"1\" Grid.Row=\"0\" ItemsSource=\"{Binding Source={StaticResource BondListKey}}\"  />" +
"</ControlTemplate>";
ccMaterial.Template = (ControlTemplate)XamlReader.Parse(template);

然后在codebehind中,我将模板设置如下:

<ContentControl x:Name="ccMaterial">
  <ContentControl.Resources>
    <x:Array x:Key="BondListKey" Type="sys:Int32" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib" />
  </ContentControl.Resources> 
</ContentControl>
   string template = "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
     "<ComboBox Grid.Column=\"1\" Grid.Row=\"0\" ItemsSource=\"{Binding Source={StaticResource BondListKey}}\"  />" +
"</ControlTemplate>";
ccMaterial.Template = (ControlTemplate)XamlReader.Parse(template);
string template=“”+
"" +
"";
ccMaterial.Template=(ControlTemplate)XamlReader.Parse(Template);
问题是,当我尝试运行它时,我得到一个异常,表示无法找到资源“BondListKey”。有人能解释为什么吗

如果您需要更多信息,请告诉我

针对约翰的评论:

我有一个选项卡项,我希望能够根据用户在表单其他地方的选择,在该选项卡中显示不同的控件。例如,如果用户选择了一辆车,我希望能够更改控制模板,以包括发动机尺寸、燃油类型等文本框,如果用户选择了橙色,我希望控制模板包括多样性和甜度。我怀疑我可以通过在选项卡上绘制所有可能的控件,然后根据datatrigger更改相关控件的可见/启用状态来获得此功能,但这可能涉及大量过滤控件(因为可能有许多用户选择类型)。理想情况下,我希望能够将所需的控件模板作为字符串提供、解析并分配给控件的模板,从而在运行时修改其内容


请让我知道这是否有意义,或者您需要任何澄清:)

StaticResource是一种静态查找,在加载时执行一次。如果当时找不到目标资源,则会出现一个错误,即您现在看到的错误。因为您正在XAML阅读器的上下文中加载模板,所以XAML中的资源不可用。在大多数情况下,修复方法是使用DynamicSource提供默认值,该值在资源可用时更新,但绑定源不是DependencyProperty,因此不能使用DynamicSource

您不必使用XamlReader,只需在XAML中声明您的XAML,并利用可用的上下文:

<ContentControl x:Name="ccMaterial">
    <ContentControl.Resources>
        <x:Array x:Key="BondListKey" Type="sys:Int32"
             xmlns:sys="clr-namespace:System;assembly=mscorlib" />
        <ControlTemplate x:Key="MyTemplate">
            <ComboBox Grid.Column="1" Grid.Row="0" ItemsSource="{Binding Source={StaticResource BondListKey}}"  />
        </ControlTemplate>
    </ContentControl.Resources>
</ContentControl>

除了ItemsSource需要列表,而不是Int32?Henk请在此处检查答案:)似乎我忽略了那里的
x:Array
。谢谢John,我将尝试一下。我对您的答案唯一关心的是,我使用xaml读取器加载模板的原因是我希望在运行时动态更改控件模板。如果我试图在运行时修改包含对xaml资源引用的控件模板,那么使用上述方法是否不会产生相同的错误?因此,如果我创建这样的控件模板,我无法访问xaml中定义的资源和控件?能否添加一些有关您试图实现的最终结果的详细信息?当您说“动态更改控件模板”时,您是在尝试更改为其他模板还是修改分配的实例?什么不起作用?在XAML中声明模板可以让您访问范围内的任何内容,所以我不知道您最后的评论是什么意思。有许多机制可以更改运行时模板行为-绑定、触发器、VisualState、模板选择器。。。但不知道你想做什么,我不能推荐任何东西。