我在几年前工作的一个符合 MVVM 的项目中遇到了类似的问题。
我有一些 XAML“资源”存储在数据库中,我需要检索它们以便将它们插入到一些 WPF 窗口或用户控件中。所以我使用了附加属性。
为简单起见,我假设您的资源位于App.xaml 中,即类似的东西:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<DockPanel x:Key="dockPanel" Margin="2">
<TextBlock Text="A description..." Margin="0, 0, 2, 0" DockPanel.Dock="Top" />
<RichTextBox />
</DockPanel>
</Application.Resources>
</Application>
所以你可以创建一个InsertXamlBehavior 类:
namespace WpfApplication1
{
public class InsertXamlBehavior
{
public static readonly DependencyProperty KeyProperty =
DependencyProperty.RegisterAttached("Key", typeof(string), typeof(InsertXamlBehavior), new UIPropertyMetadata(null, new PropertyChangedCallback(OnKeyChanged)));
public static string GetKey(DependencyObject obj)
{
return (string)obj.GetValue(KeyProperty);
}
public static void SetKey(DependencyObject obj, string value)
{
obj.SetValue(KeyProperty, value);
}
private static void OnKeyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
IAddChild addChild = dependencyObject as IAddChild;
if (addChild != null)
{
if (args.NewValue != null)
{
addChild.AddChild(App.Current.FindResource(args.NewValue));
}
}
else
{
throw new NotSupportedException();
}
}
}
}
现在您可以在窗口中轻松插入 XAML 资源:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="600">
<StackPanel>
<TextBlock Text="Here an inserted XAML resource..." Margin="2" />
<Border Margin="2" Padding="4" BorderBrush="Gray" BorderThickness="2" local:InsertXamlBehavior.Key="dockPanel" />
</StackPanel>
</Window>
当然,您可以更改 InsertXamlBehavior 以便从您喜欢的源中检索您的 XAML(例如像我这样的数据库)。