我在为 ListBox 设置数据绑定(bind)时遇到问题。我怀疑这是因为我正在尝试针对接口(interface)而不是类进行数据绑定(bind)。
我的 C# 代码:
namespace MyNamespace
{
interface IFoo
{
string Bar { get; }
}
class Fizz
{
private class Buzz : IFoo
{
public string Bar { get { return "something"; } }
}
public IEnumerable<IFoo> GetFoo()
{
List<Buzz> items = new List<Buzz>();
// Populate items
return items;
}
}
}
当我尝试对 Fizz::GetFoo()
的输出进行数据绑定(bind)时,它不起作用。我的 XAML 看起来像:
<ListBox Name="listBox1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Bar:" />
<TextBlock Text="{Binding Bar}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
当我运行它时,我看到第一个 TextBlock 的文本,但看不到第二个。我在“输出”窗口中看到类似这样的错误:
System.Windows.Data Error: Cannot get 'Bar' value (type 'System.String') from 'Buzz' (type 'MyNamespace.Fizz+Buzz'). BindingExpression: Path='Bar' DataItem='Buzz' (HashCode=100433959); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.MethodAccessException: Attempt to access the method failed: MyNamespace.Fizz+Buzz.get_Bar() at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark) at System.Reflection.RuntimePropertyInfo.InternalGetValue(PropertyInfo thisProperty, Object obj, Object[] index, StacA first chance exception of type 'System.MethodAccessException' occurred in mscorlib.dll
我是做错了什么还是我想做的事根本不可能?
最佳答案
看起来你链中的所有东西都需要公开(你的 List
需要是 List<IFoo>
而不是 List<Bar>
):
public interface IFoo
{
string Bar { get; }
}
public class Fizz
{
public class Buzz : IFoo
{
public string Bar { get { return "something"; } }
}
public IEnumerable<IFoo> GetFoo()
{
List<IFoo> items = new List<IFoo>();
// Populate items
return items;
}
}
您遇到的问题与跨程序集的反射有关。 Silverlight 代码反射(reflect)在您的内部类和接口(interface)上(类和接口(interface)是 internal
,除非另有说明)。连Buzz
需要公开,因为它仍然需要反射(reflect)那个私有(private)的类,所以它失败了。
显然,如果您不在此处使用数据绑定(bind),则代码可以正常运行。您将有权访问 IFoo
尽管Buzz
是私有(private)的。但是,不幸的是,一旦你将反射(reflection)纳入其中,你就必须开始将事情公开。
关于silverlight - 将 ListBox 绑定(bind)到 Silverlight 中的界面属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166516/