我在ListBox上使用数据绑定时遇到了问题。我怀疑是因为我试图对接口进行数据绑定,而不是类。
我的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()
的输出与数据绑定时,它无法正常工作。 我的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: 无法从'MyNamespace.Fizz+Buzz' (类型为 'System.String') 获取 'Bar' 值。BindingExpression: Path='Bar' DataItem='Buzz' (HashCode=100433959); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.MethodAccessException: 尝试访问该方法失败: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
我做错了什么还是我尝试做的事情不可能?
listBox1
实际上绑定了什么?你没有包含足够的代码。 - slugsterDataContext = fizz.GetFoo();
。这不是问题,因为消息中清楚地表明该属性存在...但存在访问冲突。 - Brian Genisio