重写 WPF 中的 DataContext

发布于 2024-12-20 02:16:02 字数 605 浏览 2 评论 0原文

我想制作一个仅适用于特定类型的DataContext 的UserControl。 为此,我正在做这样的事情:

  public new AutoSuggestViewModel DataContext 
             { get { return (AutoSuggestViewModel)base.DataContext; } 
               set { base.DataContext = value; } }

不幸的是,这往往会破坏.Net的反射,并导致控件在Visual Studio的设计视图中出错,更糟糕的是,当我使用该控件作为DataGridTemplateColumn的编辑模板的一部分时,会导致错误并且不会由于反射损坏,再次正常工作。它在 datagrid.BeginEdit() 上显示为 AmbigouslyMatchException

有谁知道解决这个问题的方法以及如何实现它。 是的,我考虑过使用另一个属性,例如 MyDataContext ,它返回强制转换 DataContext 但如果可能的话,我正在寻找更优雅的东西。

I would like to make a UserControl which works only with a specific type of DataContext.
For that purpose I am doing something like this:

  public new AutoSuggestViewModel DataContext 
             { get { return (AutoSuggestViewModel)base.DataContext; } 
               set { base.DataContext = value; } }

This unfortunately tends to break .Net's reflection and causes the control to error in design view in Visual Studio and even worse when I use the control as a part of DataGridTemplateColumn's editing template causes errors and does not work properly, again due to broken reflection. It comes out as AmbiguousMatchException on datagrid.BeginEdit()

Does anybody know a work around this problem and how to achieve that.
And yes I have thought of using another property like MyDataContext which returns cast DataContext but I am looking for something more elegant if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轻许诺言 2024-12-27 02:16:02

更优雅的做法是根本不强加于 DataContext。事实上,我不明白你为什么要这样做。为什么不直接定义一个类型正确的单独的依赖属性呢?然后,控件的使用者可以通过绑定到其数据上下文或使用任何其他标准 WPF 习惯用法来分配给它。

Something more elegant would be to not impose on the DataContext at all. In fact, it doesn't make any sense to me why you'd want to do that. Why not just define a separate dependency property that is of the correct type? Then, consumers of your control can assign to it, either through a binding to their data context, or using any other standard WPF idiom.

轻许诺言 2024-12-27 02:16:02

还有其他方法可以确保分配正确类型的对象,例如,您可以在覆盖的元数据中创建属性更改回调,检查新值的类型,如果您“不喜欢它”,则抛出异常。

There are other ways to ensure that the right kind of object is assigned, you can for example create a property changed callback in the overriden metadata, check the type of the new value and throw an exception if you "do not like it".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文