根据 属性 值动态加载 ResourceDictionary 项

Load ResourceDictionary item dynamically based on property value

是否可以根据我的视图模型中的字符串 属性 加载我的堆栈面板之一?因此,如果字符串是 MyStackPanel1,那么适当的堆栈面板将被注入到我的主窗口的网格中。

我的资源词典

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">


    <StackPanel x:Key="MyStackPanel1" Background="{Binding Color}"> 
       // Has some content     
    </StackPanel>

    <StackPanel x:Key="MyStackPanel2" Background="{Binding Color}">   
     // Has some other content
    </StackPanel>
</ResourceDictionary>

我的主窗口:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>

    </Grid>
</Window>

这里是视图模型的想法:

public class ViewModel : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;
  public string StackPanelName { get; set; };
  public string Color { get; set; };

   private void ChangedHandler(string propertyToBeChanged) {

   }
}

我想我知道如何解决这个问题。首先我定义一个资源列表:

在XAML我写:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

<Grid x:Name="Body">
    <ContentControl x:Name="Sample" ContentTemplate="{StaticResource MyResource1}"/>
</Grid>

现在在我的资源字典中:

<DataTemplate x:Key="MyResource1" x:Shared="false">
    <StackPanel>
        <TextBlock Background="{Binding background}">Hello World</TextBlock>
    </StackPanel>
</DataTemplate>

// Resource2 and so on

那么在我看来我可以做以下事情:

public void SwapResource(ContentControl contentControl, string resourceName) {
    contentControl.ContentTemplate = (DataTemplate)FindResource(resourceName);
}

问题是绑定不起作用...

您可以将 ContentControlContentTemplates 一起使用,但要使绑定正常工作,您应该设置 ContentControlContent 属性:

<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="MyResource1" x:Shared="false">
            <StackPanel>
                <TextBlock Background="{Binding background}">Hello World</TextBlock>
            </StackPanel>
        </DataTemplate>

        <!-- Resource2 and so on -->
    </ResourceDictionary>
</Window.Resources>

<Grid x:Name="Body">
    <!-- "background" is a property of the view model -->
    <ContentControl x:Name="Sample" Content="{Binding}" ContentTemplate="{StaticResource MyResource1}"/>
</Grid>