Solved

How do I do databinding in WPF - ListBox and ListView

Posted on 2007-12-05
13
17,596 Views
Last Modified: 2013-12-16
Hi,

I am using VS 2008 Beta 2 on Vista.  I am finding databinding on WPF a little difficult.  I have seen lots of examples of people binding to textboxes.  Basically I have a table users with a few columns - firstName, lastName, email.  I have a stored procedure that returns a list of users.  I have created a SqlDataAdapter that gets data and fills a DataTable dt.  I have a a listview lvUsers.  Now how do I bind the data in dt to lvUsers?  Used to be easy as control.DataSource = dt

Thanks
0
Comment
Question by:gbzhhu
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20412161
I, too, find that WPF is a strange new world, that takes a lot to learn.

Have you seen articles like this?

WPF Data Binding Tutorial
http://coredotnet.blogspot.com/2006/05/wpf-data-binding-tutorial.html

Bob
0
 
LVL 12

Author Comment

by:gbzhhu
ID: 20412549
Hi Bob,

I thought only you would be the one attempting to answer this :-)

I have seen that article and numerous others like these.

http://blogs.msdn.com/henryh/archive/2005/06/23/431846.aspx
http://msdn.microsoft.com/msdnmag/issues/07/12/DataPoints/

I have now managed to databind the ListBox.  It is displaying fields vertically, i.e

Row1
  field 1
  field 2
  field 3
Row 2
  field 1
  field 2
  field 3

And I have no styling.  Having used to doing the styling via property pages and also creating templates via GUI, I am now wondering why we have to code GUI in XAML which is simple looking language but certainly not easy.

What I was attempting to do was load a list of users from DB and show them in List control (ListBox, ListView etc) then user types a few characters on textbox I use for filtering then I would run some LINQ to get users whose names start with the characters entered.  all works apart from styling (and when LINQ is applied to filter users I get the right number of users back but the ListBox although it contains the correct number of users does not display them - there must some tweaking I am missing).  All in all it is weird way of doing things

I am just looking at the web for a WPF book.  It is said that every Windows Forms developer must learn WPF so better start now!

Hassan
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20412848
XAML is a completely different beast than anything that I have seen in a long time.  Have you seen or used anything like Expression?  

What kind of styling are you looking for?

Bob
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
LVL 12

Author Comment

by:gbzhhu
ID: 20412972
Yeah I agree about XAML!  I guess it is a matter of getting used to it.  I prefer object based priogramming as opposed to declarative.

Do you mean Expression Blend?  I haven't used it.  Does it come with VS 2008 (I am using VS 2008 Beta 2)?

Styling wise I am after 2 types of styling, basic which I should be able to achieve at some point and fancy which may not be possible

Basic
 - display header row with column header text
 - display fields as columns horizontally like a datagrid would

Fancy (as above plus)
 - header bgcolour - gradient
 - borders and gradient colour on selected rows

That'd do for now :-)
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20413103
Yeah, Expression Blend ;)

It is a separate application from VS 2008, but comes in the MSDN subscription.  It makes it easier to style XAML.

How is your ListBox declared?

Bob
0
 
LVL 12

Author Comment

by:gbzhhu
ID: 20413160
I see.  We only received Beta 2 and we are waiting for the RTM stuff.  I will install Expression Blend then and hope it helps.

My whole XAML below

<Window x:Class="WpfApp1.Users"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Users" Height="402" Width="495">
    <Grid>
        <Button Height="25" HorizontalAlignment="Left" Margin="18,0,0,24" Name="btnUsers" VerticalAlignment="Bottom" Width="109" Click="btnUsers_Click">Get Users</Button>
        <TextBox Height="25" Margin="140,0,94,25" Name="txtUser" VerticalAlignment="Bottom" />
        <ListBox Margin="10,10,12,66" Name="listBox1" ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=firstName}" />
                        <TextBlock Text="{Binding Path=lastName}"/>
                        <TextBlock Text="{Binding Path=email}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBlock Height="20" HorizontalAlignment="Left" Margin="26,0,0,3" Name="textBlock1" VerticalAlignment="Bottom" Width="104" />
        <TextBox Height="20" Margin="140,0,188,2" Name="textBox1" VerticalAlignment="Bottom" />
    </Grid>

</Window>


And my whole code behind minus using directives

    public partial class Users : Window
    {
        DataTable dt = new DataTable();

        public Users()
        {
            InitializeComponent();
           
            this.Loaded += new RoutedEventHandler(Users_Loaded);
        }

        void Users_Loaded(object sender, RoutedEventArgs e)
        {
            SqlDataAdapter adaptor = new SqlDataAdapter("cms_getUsers", "server=dbserver;database=bayer_bioscience;user id=webBayer;password=password;");
            adaptor.Fill(dt);
            DataContext = dt;

            //this.listView1.DataContext = ds.Tables[0];
            //Binding bind = new Binding();
            //bind.Source = ds.Tables[0];
            //this.listView1.SetBinding(ListView.ItemsSourceProperty, bind);
           
        }

        private void btnUsers_Click(object sender, RoutedEventArgs e)
        {
            var query = from r in dt.AsEnumerable()
                        where r.Field<string>("lastName").StartsWith(this.txtUser.Text)
                        select r;

            //DataContext = query;
            //listBox1.DataContext = DataContext;
        }
    }

0
 
LVL 12

Author Comment

by:gbzhhu
ID: 20413205
Bob,

Are you any good at Mobile dev? Windows Mobile 5 and CF 2.0?

I have this issue that I couldn't fix for 5 months now !!!!
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 20413305
Here is a LinearGradientBrush for the Background:

        <ListBox Margin="10,10,12,66" Name="listBox1" ItemsSource="{Binding}">
            <ListBox.Background>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,5">
                    <GradientStop Color="Blue" Offset="0.0" />
                    <GradientStop Color="Red" Offset="0.25" />
                    <GradientStop Color="White" Offset="0.75" />
                </LinearGradientBrush>
            </ListBox.Background>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=firstName}" />
                        <TextBlock Text="{Binding Path=lastName}"/>
                        <TextBlock Text="{Binding Path=email}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

The two properties for the gradient orientation are StartPoint and EndPoint.  For vertical, set StartPoint.X = EndPoint.X, and EndPoint.Y > StartPoint.Y, and for horizontal, reverse that.  For diagonal, you could use 0,0 and 1,1.

Bob
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20413355
>>I have this issue that I couldn't fix for 5 months now !!!!
Is there a question open?

Bob
0
 
LVL 12

Author Comment

by:gbzhhu
ID: 20413432
I had a question open but it is now closed - I'll explain.

Basically this issue doesn't stop program from running.  Just that when an exception occurs I get a generic error explained here
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2460541&SiteID=1

I can open a question if you could look into it or find others whop are good at this topic.  I only know of one Mikal613 but he/she could not fix this one.

by the way, tyhe gradient colour you showed me is brilliant! thanks
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20413523
You would have to open another question, and give me the URL for it before I could help you.

Bob
0
 
LVL 12

Author Comment

by:gbzhhu
ID: 20629845
Sorry Bob.  left this open too long.  I have abandoned my WPF  research for now.  I bought a book and want to read it first then get back to it.  Thanks for helping as always

H
0

Featured Post

Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

Question has a verified solution.

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

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

634 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