2011-05-15 69 views
0

Im在Silverlight中設置數據綁定時遇到了一些問題。Silverlight DataBinding MVVM

我試圖使用MVVM的方法,並發現了一些很好的例子,所以我創建了我的視圖和我的ViewModel,我創建了一些類將用來包含數據和一個填充類。

首先我的視圖模型的樣子:

public class MainPageVM : INotifyPropertyChanged 
    { 
     ObservableCollection<Item> Items; 
     public MainPageVM() 
     { 
      InitializeItems InitItems = new InitializeItems(); 
      InitItems.GenerateItemList(out Items); 
      RaiseProertyChanged("Items"); 
     } 
     public string test = "Binding Test"; 

     public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 

     private void RaiseProertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 

然後在我看來,我有:

<UserControl.Resources> 
    <viewmodel:MainPageVM x:Key="ViewModel" />  
</UserControl.Resources> 
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}"> 
    <StackPanel> 
     <TextBlock Text="{Binding test}"/> 
     <ListBox ItemsSource="{Binding Items}" 
      Width="200" 
      Height="200"> 
      <ListBoxItem Width="190" Height="20"> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding ItemName}"/> 
        <TextBlock Text="-"/> 
        <TextBlock Text="{Binding ItemID}"/> 
       </StackPanel> 
      </ListBoxItem> 
     </ListBox> 
    </StackPanel> 
</Grid> 

我加的斷點,我知道我的ObservableCollection,即時通訊試圖綁定到被填充,但什麼都沒有綁定,在錯誤窗口中我只是得到xxx屬性不存在於MainPageVM中。

這裏的任何建議都會很棒,因爲我可能會丟失什麼,這是我的第一個silverlight應用程序。

謝謝

+0

爲什麼有人低估了這一點? – Town 2011-05-15 20:43:04

回答

2

項目需要是公共財產。與您的測試領域相同。在Silverlight中,您只能綁定到公共屬性。

此外,通常在這些屬性的Setter中,您將引發屬性更改事件。這告訴Silverlight運行時使用該屬性的新值刷新綁定到該屬性的控件。

+0

謝謝,我認爲它可以讓我突出綁定到公共變量而不是屬性。 – FCat 2011-05-15 20:29:13

+0

歡迎您! – 2011-05-15 20:32:10