Datatable for binding various data sources to WPF

Source: Internet
Author: User

1. Binding is the core of WPF. WPF data sources include:

1. datatable In ADO. net

2. XML Data Source

3. Object Data Source

4. element control attributes

Ii. WPFBind various data source Indexes

Datatable for binding various data sources to WPF

Object Data Sources bound to various data sources in WPF

XML data sources bound to various data sources in WPF

Element control attributes bound to various data sources in WPF

WPF binding Basics

3. Here are some simple examples.

1. Bind a datatable data source to ListBox

Front-end code

    <ListBox Margin="12,32,12,329" ItemsSource="{Binding}" Name="listBox1">            <ListBox.ItemTemplate>                <DataTemplate>                               <Grid>                        <Grid.ColumnDefinitions>                            <ColumnDefinition Width="0.5*"/>                            <ColumnDefinition Width="0.5*"/>                            <ColumnDefinition Width="0.5*"/>                        </Grid.ColumnDefinitions>                          <TextBlock Text="{Binding Path=ID}"/>                        <TextBlock  Text="{Binding Path=Name}"/>                        <TextBlock Grid.Column="1" Text="{Binding Path=Age}" Background="{Binding Path=Age, Converter={StaticResource BackgroundConverter}}"/>                    </Grid>                </DataTemplate>            </ListBox.ItemTemplate>        </ListBox>

Background code:

Public window1 () {initializecomponent (); listbox1.datacontext = getdatatable (); // use the itemssource format // listbox1.itemssource = getdatatable (). defaultview; listbox1.selectedindex = 0 ;}

The following describes how to create a datatable data source. You can also connect to the database to obtain the data source.

Private datatable getdatatable () {datatable DATA = new datatable ("mydatatable"); datacolumn id = new datacolumn ("ID"); // the ID of the first column. datatype = system. type. getType ("system. int32 "); // ID. autoincrement = true; // auto increment ID data. columns. add (ID); // set the primary key datacolumn [] keys = new datacolumn [1]; keys [0] = ID; data. primarykey = keys; data. columns. add (New datacolumn ("name", typeof (string); // the second column of data. columns. add (New datacolumn ("Age", typeof (string); // The third column of data. rows. add (1, "xiaom", "20"); data. rows. add (2, "xiaof", "122"); data. rows. add (3, "xiaoa", "29"); data. rows. add (4, "xiaob", "102"); return data ;}

Below is the type conversion

    public class BackgroundConverter : IValueConverter    {        #region IValueConverter Members        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)        {            Color color = new Color();            int num = int.Parse(value.ToString());            if (num > 100)                color = Colors.Yellow;            else if (num < 50)                color = Colors.LightGreen;            else                color = Colors.LightPink;            return new SolidColorBrush(color);        }        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)        {            throw new NotImplementedException();        }        #endregion    }

  

:

2. Use listview to bind the datatable data source. The data source is the same as the first one. The difference is:

Front-end code:

<Listview Height = "262" margin = "-, 0, 12, 39 "verticalalignment =" bottom "itemssource =" {binding} "name =" listview2 "horizontalalignment =" center "> <listview. view> <gridview> <gridviewcolumn header = "no." displaymemberbinding = "{binding Path = ID}" width = "100"/> <gridviewcolumn header = "name" displaymemberbinding = "{ binding Path = Name} "width =" 100 "/> <gridviewcolumn header =" Age "width =" 100 "> <gridviewcolumn. celltemplate> <datatemplate> <textblock grid. column = "1" text = "{binding Path = age}" foreground = "{binding Path = age, converter = {staticresource backgroundconverter} "/> </datatemplate> </gridviewcolumn. celltemplate> </gridviewcolumn> </gridview> </listview. view> </listview>

  

Background code:

  listView2.DataContext = GetDataTable().DefaultView;

:

 

3. If the data source is already a able, use the following format to retrieve the result:

            DataTable dt = GetDataTable();            listView2.ItemsSource =                from row in dt.Rows.Cast<DataRow>()                where Convert.ToString(row["Name"]).StartsWith("XiaoF")                select new Student()                {                    ID = int.Parse(row["ID"].ToString()),                    Name = row["Name"].ToString(),                    Age = row["Age"].ToString()                };

Others remain unchanged. The above code is to retrieve data starting with xiaof with only one data entry. As follows:

 

  

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.