Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How do I do databinding in WPF - ListBox and ListView

Posted on 2007-12-05
13
Medium Priority
?
17,604 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
  • 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
Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
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 2000 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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Integration Management Part 2
Loops Section Overview

782 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