设计时的数据模板
在我第一次尝试使用 WPF 时,我做得有点过头了:
我有一个对象需要不同的 DataTemplate,具体取决于其属性之一。换句话说,if (object.property=="multi")
那么模板应该是一个组合,等等。
现在我已经继续,显然使用了 DataTemplateSelector 来应用所需的模板。并且在运行时有效。在设计时vs2008设计者抱怨,因为DataTemplateSelector使用Application.Current.MainWindow.FindResource来找到合适的模板来应用,显然设计时的Application.Current不是我的应用程序,所以找不到资源,所以设计者抛出异常。
鉴于我希望其他人能够更改模板,我确实需要设计时支持。
我的问题有解决办法吗? 我的整个方法完全有缺陷吗?
In one of my first attempts with WPF I went a bit too far:
I have an object that needs a different DataTemplate depending on one of its properties. In other words if (object.property=="multi")
then the template should be a combo, etc.
Now I 've went ahead and obviously used a DataTemplateSelector to apply the required template. And in runtime that works. In design-time vs2008 designer complains because the DataTemplateSelector uses Application.Current.MainWindow.FindResource in order to find the appropriate template to apply and obviously Application.Current in design time is not my application, so the resource cannot be found, so the designer throws an exception.
Given that I would like other people to be able to change the templates, I really need design-time support for this.
Is there a solution to my problem?
Is my whole approach completely flawed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这只是我的想法,所以我不确定它是否有效,但是使用数据触发器并使用设置器分配适当的模板怎么样。
像“
This is just off the top of my head so i'm not sure if it works, but what about using datatriggers and assign the appropriate template with a setter.
Something like"
我想我已经找到了我的问题的答案(尽管它有它自己的问题)。
DataTemplateSelector 应该具有公共属性来保存可能的模板。当您在 XAML 中实例化 DataTemplateSelector 时,您将向其传递相关模板,例如
这实现了设计时支持。另一方面,它要求您在实例化选择器时知道可能的模板是什么,但情况并非总是如此。
I think I have found the answer to my question (though it has problems of its own).
The DataTemplateSelector should have public properties to hold the possible templates. When you instantiate the DataTemplateSelector in XAML you pass it the relevant templates, something like
This achieves design-time support. On the other hand it requires that you know what are the possible templates when you instantiate the selector, which is not always the case.
您可以将依赖属性添加到每种模板的模板选择器中,并在 XAML 中引用模板:
或者,只需在后面的代码中实例化并分配模板选择器。
You could add a dependency property to your template selector for each kind of template and reference the templates in XAML:
Or, just instantiate and assign the template selector in the code behind.