我遇到的問題讓我的數據綁定適用於ListBox。我懷疑這是因爲我試圖對一個接口而不是一個類進行數據綁定。將列表框綁定到Silverlight中的界面屬性
我的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: 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
我做錯了什麼,或者我正在嘗試做什麼不可能?
您可以發佈您使用GetFoo()初始化DataContext的代碼嗎? – decyclone 2011-03-02 11:06:54
listBox1實際上綁定了什麼?你沒有包含足夠的代碼。 – slugster 2011-03-02 11:16:17
我認爲可以安全地假設他正在設置DataContext = fizz.GetFoo();'這不是問題,因爲消息中明確指出屬性存在......但存在訪問衝突。 – 2011-03-02 11:34:56