我想出了一个合理可接受的解决方法来解决这个问题,因为它似乎没有在 Blend 4 中得到修复:
在 XAML UserControl 的构造函数中,只需添加它需要的资源,前提是您在 Blend 中处于设计模式。这可能只是定位器,也可能是适当的样式和转换器。
public partial class OrdersControl : UserControl
{
public OrdersControl()
{
// MUST do this BEFORE InitializeComponent()
if (DesignerProperties.GetIsInDesignMode(this))
{
if (AppDomain.CurrentDomain.BaseDirectory.Contains("Blend 4"))
{
// load styles resources
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(System.IO.Path.Combine(Environment.CurrentDirectory, "Resources/Styles.xaml"), UriKind.Absolute);
Resources.MergedDictionaries.Add(rd);
// load any other resources this control needs such as Converters
Resources.Add("booleanNOTConverter", new BooleanNOTConverter());
}
}
// initialize component
this.InitializeComponent();
}
可能会有一些边缘情况,但在我得到一个大红色错误符号之前的简单情况下,它对我来说工作正常。我很想看到关于如何更好地解决这个问题的建议,但这至少允许我为用户控件设置动画,否则这些控件会显示为错误。
您还可以提取资源的创建App.xaml.cs
:
internal static void CreateStaticResourcesForDesigner(Control element)
{
if (AppDomain.CurrentDomain.BaseDirectory.Contains("Blend 4"))
{
// load styles resources
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(System.IO.Path.Combine(Environment.CurrentDirectory, "Resources/Styles.xaml"), UriKind.Absolute);
element.Resources.MergedDictionaries.Add(rd);
// load any other resources this control needs
element.Resources.Add("booleanNOTConverter", new BooleanNOTConverter());
}
}
然后在控件中在 InitializeComponent() 之前执行此操作:
// create local resources
if (DesignerProperties.GetIsInDesignMode(this))
{
App.CreateStaticResourcesForDesigner(this);
}
注意:在某个时间点,这对我不起作用,我最终对 Styles.xaml 的路径进行了硬编码,因为我试图弄清楚我在哪个目录中感到沮丧。
rd.Source = new Uri(@"R:\TFS-PROJECTS\ProjectWPF\Resources\Styles.xaml", UriKind.Absolute);
我确信我可以在 5 分钟的工作中找到正确的路径,但如果你像我一样无所适从,试试这个吧!