Im having some problems with setting up databinding in Silverlight.
Im trying to use the MVVM approach and found some nice examples, So Ive created my View and my ViewModel, I created some classes Im going to use to contain the data and one to populate the classes.
Firstly my ViewModel looks like:
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));
}
}
}
And then in my View i have :
<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">
开发者_如何学Go <TextBlock Text="{Binding ItemName}"/>
<TextBlock Text="-"/>
<TextBlock Text="{Binding ItemID}"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
</Grid>
I added breakpoints and I know my ObservableCollection that im trying to bind to is being populated but nothing binds, in the error window im just getting xxx property doesnt exist in MainPageVM.
Any advice here would be great as im a bit lost as to what could be going on, and this is my first silverlight application.
Thanks
Items needs to be a public property. Same with your test field. In Silverlight you can only bind to public properties.
Also, typically in the Setter of those properties you raise the property changed event. This tells the Silverlight runtime to refresh the controls that are bound to that property with the new values of that property.
精彩评论