【问题标题】:WPF/Silverlight DataBinding to interface property (with hidden implementation)WPF/Silverlight DataBinding 到接口属性(具有隐藏实现)
【发布时间】:2010-05-22 14:28:16
【问题描述】:

我有以下 (C#) 代码

namespace A
{
  public interface IX { bool Prop { get; set; } }
  class X : IX { public bool Prop { ... } } // hidden implementation of IX
}

namespace B
{
  ..
  A.IX x = ...;
  object.DataContext = x;
  object.SetBinding(SomeDependencyProperty, new Binding("Prop"));
  ..
}

所以我有一个带有属性“Prop”的接口的隐藏实现,我需要在代码中绑定到这个属性。

我的问题是除非我公开 X 类,否则绑定不起作用。

有没有办法解决这个问题?

【问题讨论】:

标签: c# wpf silverlight data-binding


【解决方案1】:

我相信您在 Silverlight 中执行此操作,因为在那里无法绑定到非公共成员。但是它在 WPF 中。

因此,对于 Silverlight,您应该公开您的课程。

【讨论】:

  • 是的,这违反了 Silverlight 的访问规则。如果用户可以绑定到这些值并设置/获取它们,那么阻止私有/受保护/内部反射有什么意义?
【解决方案2】:

有一个很好的理由让类在内部实现公共接口。这强制执行基于接口的编程。 .Net 是关于接口的,而不是类。经验法则:当可以公开接口时,切勿公开具体的非原始类型。

有一种绑定语法允许 XAML 编译器将对象强制转换为接口。在另一篇文章中提到过:

{Binding Path=(mynamespacealias:IMyInterface.MyValue)}

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 2011-03-19
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多