2012-06-01 59 views
0

我無法從綁定到ListBox的自定義對象中的可觀察集合中獲取任何顯示。當我在我的視圖模型中有一個字符串集合時,這工作正常,但當我嘗試通過自定義對象訪問屬性時沒有名稱顯示。我在輸出窗口中沒有收到任何錯誤。將嵌套屬性綁定到列表框的數據

這裏是我的代碼:

自定義對象

public class TestObject 
{ 
    public ObservableCollection<string> List { get; set; } 

    public static TestObject GetList() 
    { 
     string[] list = new string[] { "Bob", "Bill" }; 

     return new TestObject 
     { 
      List = new ObservableCollection<string>(list) 
     }; 
    } 
} 

的XAML

<Window x:Class="TestWPF.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <ListBox Height="100" HorizontalAlignment="Left" Margin="120,61,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding Path=TObj.List}" /> 
</Grid> 

Xaml.cs

public partial class MainWindow : Window 
{ 
    private ModelMainWindow model; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     model = new ModelMainWindow(); 
     this.DataContext = model; 
     this.Loaded += new RoutedEventHandler(MainWindow_Loaded); 
    } 

    public void MainWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     this.model.Refresh(); 
    } 
} 

視圖模型

public class ModelMainWindow : INotifyPropertyChanged 
{ 
    private TestObject tObj; 

    public event PropertyChangedEventHandler PropertyChanged; 

    public TestObject TObj 
    { 
     get 
     { 
      return this.tObj; 
     } 

     set 
     { 
      this.tObj = value; 
      this.Notify("Names"); 
     } 
    } 

    public void Notify(string name) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

    public void Refresh() 
    { 
     this.TObj = TestObject.GetList(); 
    } 
} 

回答

1

無法綁定到私有屬性。此外,更改通知會將目標地址設爲錯誤,將"Names"更改爲"TObj"。 (另外我會建議使List屬性只能得到(由readonly字段支持),或者實施INoptifyPropertyChanged,以便更改不會丟失)

+0

我已將此更改爲公開,但我仍未收到結果。我編輯了我的問題來反映這一點。 – Jason

+1

@Jason:那麼,你可能也想正確實現['INPC'](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx),否則綁定將不會如果屬性更改,則更新您爲「名稱」而不是「TObj」進行了更改。 –

+0

杜,就是這樣。不能相信我錯過了這一點。謝謝! – Jason

0

List是私有的。使其成爲公共財產,否則WPF無法看到它。

+0

我已將此更改爲公開,但我仍然沒有收到結果。我編輯了我的問題來反映這一點。 – Jason