简体   繁体   English

WPF / Silverlight DataBinding到接口属性(具有隐藏实现)

[英]WPF/Silverlight DataBinding to interface property (with hidden implementation)

I have the following (C#) code 我有以下(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"));
  ..
}

So I have a hidden implementation of an interface with a property "Prop" and I need to bind to this property in code. 因此,我具有属性“ Prop”的接口的隐藏实现,并且需要在代码中绑定到该属性。

My problem is that the binding isn't working unless I make class X public. 我的问题是,除非我公开X类,否则绑定将不起作用。

Is there any way around this problem? 有什么办法可以解决这个问题?

I believe you are doing this in Silverlight, because binding to not public members is not possible there. 我相信您是在Silverlight中执行此操作的,因为在那里不可能绑定到非公共成员。 However it is in WPF. 但是在WPF中。

So for Silverlight you should make your class public. 因此,对于Silverlight,您应该公开您的课程。

There is a very good reason for making classes implementing public interfaces internal. 使类实现内部公共接口的理由非常充分。 This enforces interface-based programming. 这将强制执行基于接口的编程。 .Net is all about interfaces, not classes. .Net全部与接口有关,而不是类。 Rule of thumb: Never expose an concrete, non-primitive type when one can expose an interface. 经验法则:当可以公开接口时,切勿公开具体的非原始类型。

There is a binding syntax that allows one to get the XAML compiler to cast an object to an interface. 有一种绑定语法,该语法允许一个XAML编译器将对象强制转换为接口。 It's been mentioned in another post: 在另一篇文章中提到了它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM