Silverlight Data Binding for Collection in Stack Panel

Posted by Blake Blackwell on Stack Overflow See other posts from Stack Overflow or by Blake Blackwell
Published on 2010-04-26T21:53:22Z Indexed on 2010/04/26 22:03 UTC
Read the original article Hit count: 273

Filed under:
|
|

I'm new to Silverlight, so I don't have a complete grasp of all the controls at my disposal. What I would like to do is use databinding and a view model to maintain a collection of items. Here is some mock code for what I'd like to do:

Model

  public class MyItem
    {
       public string DisplayText { get; set; }
       public bool Enabled { get; set; }
    }

ViewModel

public class MyViewModel : INotifyPropertyChanged
{
      private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>();
      public ObservableCollection<MyItem> MyItems
      {
          get { return _myItems; }
          set 
          { 
               _myItems = value
               NotifyPropertyChanged(this, "MyItems");
           } 
      }  
}

View

<Grid x:Name="LayoutRoot" Background="White">
        <StackPanel ItemsSource="{Binding MyItems}">            
            <StackPanel Orientation="Horizontal">
                <CheckBox "{Binding Enabled, Mode=TwoWay}"></CheckBox>
                <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" />
            </StackPanel>                
        </StackPanel>        
    </Grid>

So my end goal would be that every time I add another MyItem to the MyItems collection it would create a new StackPanel with checkbox and textblock. I don't have to use a stack panel but just thought I'd use that for this sample.

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about mvvm