是否可以根据viewmodel中的字符串属性加载我的一个stackpanel?因此,如果string是MyStackPanel1,那么适当的stackpanel将被注入我主窗口的网格中。
我的资源字典
<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>
这里有一个viewmodel的想法:
public class ViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public string StackPanelName { get; set; };
public string Color { get; set; };
private void ChangedHandler(string propertyToBeChanged) {
}
}
答案 0 :(得分:1)
我想我知道如何解决这个问题。首先,我定义了一个资源列表:
在XAML中我写道:
.pack(side="left", expand="true", fill="x", anchor="n")
现在在我的资源词典中:
<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
问题是绑定不起作用......
答案 1 :(得分:1)
您可以将ContentControl
与ContentTemplates
一起使用,但要使绑定生效,您应该设置Content
的{{1}}属性:
ContentControl