Wednesday, September 26, 2012

Binding to Listbox programattically in silverlight

Binding to Listbox programattically in silverlight

I want a listbox that will show all the images and text "layers" that I have on my Canvas in silverlight. The code I have currently crashes when I try to view the listbox or when I'm viewing the listbox when I add an element. I can't figure out why. Can someone point me in the right direction with this?

XML -

                            <Grid DataContext="{Binding Path=Project}">                                 ...                                 ...                                 <TextBlock Name="textBlock1" Text="Layers" Margin="18,16,0,0" />                                  <StackPanel Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2">                                     <ListBox ItemsSource="{Binding Path=Elements}" Height="175" Name="listBox1" Width="172"/>                                 </StackPanel>                              </Grid> 

Project.cs

        //List of elements     private ObservableCollection<FrameworkElement> elements;     public ObservableCollection<FrameworkElement> Elements     {         get { return elements; }         set         {             elements = value;             NotifyPropertyChanged("Elements");         }     } // An example of how an element is added to the Elements collection // There are also image elements added similarly private void AddTextElement(object param)     {         TextBlock textBlock = new TextBlock();         textBlock.Text = "New Text";         textBlock.Foreground = new SolidColorBrush(Colors.Gray);         textBlock.FontSize = 25;         textBlock.FontFamily = new FontFamily("Arial");         textBlock.Cursor = Cursors.Hand;         textBlock.Tag = null;           this.Elements.Add(textBlock);         numberOfElements++;           this.SelectedElement = textBlock;         this.selectedTextElement = textBlock;     } 

Answers & Comments...

Answer: 1

One reason might be, because you bind using Path property in your Grid element.

You should use binding source, and set your Project object as a staticresource which you can point to when you call binding source.

Like this:

<Window     xlmns:local="NamespaceOfMyProject">      <Window.Resources>         <local:Project x:key="MyProjectResource" />     </Window.Resources>      <Grid DataContext="{Binding Source={StaticResource MyProjectResource}}>     ....     </Grid>     .... </Window> 

Reason is: You use "Source" when you point to objects, and "Path" when you point to properties.

Another way to set the DataContext is to do it in the codebehind, using this C# code. But first give your grid a name, so it can be referenced in the codebehind:

<Grid x:Name="myGrid"> 

Codebehind:

myGrid.DataContext = new Project(); 
by : Johnnyhttp://stackoverflow.com/users/1640121




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog