?
Solved

Silverlight Listbox  Binding

Posted on 2009-12-18
11
Medium Priority
?
915 Views
Last Modified: 2013-11-12
I'm trying to get a simple list of T to bind to a listbox. The listbox is binding but the text that I'm trying to display is not displaying. You can choose between items and if you debug with some extra code you can pull the data from the class object.
<UserControl x:Class="testlistbox.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot">
        <ListBox x:Name="PersonList" ItemsSource="{Binding ''}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding FirstName}" />
                        <TextBlock Text="{Binding LastName}" />

                    </StackPanel>
                </DataTemplate>

            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

namespace testlistbox
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            InitializeComponent();
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {


            PersonList.DataContext = MakePersonList();
            PersonList.SelectedIndex = -1;
           
        }
        private static List<Person> MakePersonList()
        {
            return (new List<Person>()
            {
               new Person() { FirstName = "John", LastName = "Smith" },
               new Person() { FirstName = "John", LastName = "Jones" }
            });

        }
      
    }
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        
    }
}

Open in new window

0
Comment
Question by:MCKreed
  • 7
  • 4
11 Comments
 
LVL 13

Expert Comment

by:Ashok
ID: 26087656
<UserControl x:Class="ListBoxFromClass.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    xmlns:src="clr-namespace:ListBoxFromClass">
  <Grid x:Name="LayoutRoot">
      <Grid.Resources>
        <src:People x:Key="person"/>
      </Grid.Resources>
      <ListBox ItemsSource="{StaticResource person}" Width="350" Height="200" >
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding FirstName}" />
              <TextBlock Text=", " />
              <TextBlock Text="{Binding LastName}" />
            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
  </Grid>
</UserControl>

namespace ListBoxFromClass
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
       
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Person(String firstName, String lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

    public class People : List<Person>
    {
        public People()
        {
            Add(new Person("Michael", "Anderberg"));
            Add(new Person("Chris", "Ashton"));
        }
    }
}

HTH
Ashok
0
 
LVL 13

Expert Comment

by:Ashok
ID: 26087701
MCKreed,

I think you could make it work with your existing source code with little modifications.  I am also new to Silverlight and C#.
The problem was how the binding.  I would like to see it work with your code.  I spent two hours to figure out this.

Thanks,
Ashok
0
 
LVL 13

Expert Comment

by:Ashok
ID: 26088590
MCKreed,

Here is your style coding (without parametrized constructor) SHORT SYNTAX.....

namespace ListBoxFromClass
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class People : List<Person>
    {
       public People()
       {
           Add(new Person() { FirstName = "John", LastName = "Smith" });
           Add(new Person() { FirstName = "Chris", LastName = "Jones" });
       }
    }
}

HTH
Ashok
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 1

Author Comment

by:MCKreed
ID: 26090710
The 2 lines below, well the resource tag causes an expception.
Exception: XamlParseException
Message: "AG_E_PARSER_BAD_TYPE [Line: 12 Position: 36]"
StackTrace: "   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)\r\n   at testlistbox.MainPage.InitializeComponent()\r\n   at testlistbox.MainPage..ctor()"

I tried all the other mods, setting the itemsource or datacontext in the Page Loaded event. I get the same results, with the added comma. The list binds the data but will not display any text.


xmlns:src="clr-namespace:testlistbox"
 <src:People x:Key="p" />

Open in new window

0
 
LVL 1

Author Comment

by:MCKreed
ID: 26090743
Here's an image of what the binding with no text looks like.
listbox.jpg
0
 
LVL 13

Accepted Solution

by:
Ashok earned 2000 total points
ID: 26091624
Believe me.  It works 100%.

Did you copy complete code from my XAML and XAML.CS files?

If not, do this first.  Create new Project, give exactly same file names (leave default MainPage.xaml).
Delete everything in XAML and copy and paste.  Do samething with xaml.cs file.

Make sure ListBox shows data.  Let me know what happens.

Then try to modify it.

HTH
Ashok
0
 
LVL 13

Expert Comment

by:Ashok
ID: 26091634
See attached image.
ListBox-Scr.jpg
0
 
LVL 1

Author Comment

by:MCKreed
ID: 26093151
I did the copy and paste thing with your code and it worked fine, so I decided to start from scratch and re-wrote the code. The second time it worked fine. I have gone back and forth trying to find the difference but cannot find anything.

Here are the 2 solutions if you want to take a look:

Working Solution
http://bolsterfarm.com/downloads/working.zip

Non-Working Solution
http://bolsterfarm.com/downloads/notworking.zip

0
 
LVL 13

Expert Comment

by:Ashok
ID: 26095204
I will check and let you know in a few days.

Thanks,
Ashok
0
 
LVL 1

Author Comment

by:MCKreed
ID: 26101214
I figured out what the problem was. The UI cannot access the person class if the class is not public.

Everything else was fine.
0
 
LVL 13

Expert Comment

by:Ashok
ID: 26101346
Oh, good.  That means I will not have to check.

Thanks,
Ashok
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to programmatically preset the "Pages per Sheet" option that's available with most printer drivers.   This setting lets you do "n-Up" printing, where two, four, or more pages are printed on each sheet of paper. If your …
As more and more people are shifting to the latest .Net frameworks, the windows presentation framework is gaining importance by the day. Many people are now turning to WPF controls to provide a rich user experience. I have been using WPF controls fo…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question