2011-03-02 59 views
3

我遇到的問題讓我的數據綁定適用於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 

我做錯了什麼,或者我正在嘗試做什麼不可能?

+1

您可以發佈您使用GetFoo()初始化DataContext的代碼嗎? – decyclone 2011-03-02 11:06:54

+1

listBox1實際上綁定了什麼?你沒有包含足夠的代碼。 – slugster 2011-03-02 11:16:17

+0

我認爲可以安全地假設他正在設置DataContext = fizz.GetFoo();'這不是問題,因爲消息中明確指出屬性存在......但存在訪問衝突。 – 2011-03-02 11:34:56

回答

4

它看起來像你的一切鏈必須是公共的(和你的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代碼反映了您的內部類和接口(除非另有說明,類和接口都是internal)。即使Buzz需要公開,因爲它仍然需要反思這個私人的類,所以它失敗了。

很明顯,如果你沒有在這裏使用數據綁定,代碼將工作正常。即使Buzz是私密的,您也可以訪問IFoo。但是,一旦你對這些組合進行了反思,不幸的是你必須開始公佈事情。

+0

這爲我解決了,謝謝!請注意,我不必將列表中的項目類型更改爲列表。 – brantonb 2011-03-02 21:01:19

1

問題是您的Buzz類是私有的,因此綁定引擎無法訪問該類的成員來執行綁定。

+1

這是一個明顯的結論,但可能不是唯一的結論 - 即ListBox的datacontext也可能全部搞砸了。 – slugster 2011-03-02 11:26:52

+0

是的,如果我錯了,那麼海報總是可以發表評論,並告訴我,我的解決方案不起作用,我們可以努力尋求解決方案:) – 2011-03-02 11:33:17

+0

@slugster:我想,但他在那裏發佈的錯誤消息會使它清楚這是一個訪問衝突。另外,即使DataContext設置正確(公平的假設),我們也知道這些代碼將不起作用,因爲所有事情都需要公開 - 接口,外部類和內部類 - 以便反射工作。 – 2011-03-02 11:58:23