Data Binding (part 2, advanced), WPF
The new C++ posts will take a lot time. The C# posts are shorter for the next three weeks. Today I created a DataGrid and three TextBoxes. They are all linked together with pretty much no code. You can even add new items to the list. Check it out!
<Window x:Class="WpfDatabinding2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="26*" /> <ColumnDefinition Width="192*" /> <ColumnDefinition Width="285*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="10*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <DataGrid AutoGenerateColumns="True" Grid.ColumnSpan="3" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" ColumnHeaderHeight="30"> </DataGrid> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}" /> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Owner}" /> <TextBox Grid.Column="1" Grid.Row="3" Text="{Binding Age}" /> </Grid> </Window>
using System.Collections.Generic; using System.Windows; using System.Windows.Documents; namespace WpfDatabinding2 { public partial class MainWindow : Window { public class Dog { public string Name { get; set; } public double Age { get; set; } public string Owner { get; set; } } // class public MainWindow() { InitializeComponent(); List<Dog> lDogs = new List<Dog>(); lDogs.Add(new Dog() { Name = "Spike", Owner = "Granny", Age = 12.6 }); lDogs.Add(new Dog() { Name = "Pluto", Owner = "Mickey Mouse", Age = 7.0 }); lDogs.Add(new Dog() { Name = "Snoopy", Owner = "Charlie Brown", Age = 5.3 }); lDogs.Add(new Dog() { Name = "Lassie", Owner = "Rudd Weatherwax", Age = 8.5 }); this.DataContext = lDogs; } // } // class } // namespace
Hard to believe, but this is it. Code does not have to be long to be powerful. The magic mostly comes from these lines:
<DataGrid AutoGenerateColumns="True" Grid.ColumnSpan="3" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" ColumnHeaderHeight="30"> </DataGrid> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}" /> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Owner}" /> <TextBox Grid.Column="1" Grid.Row="3" Text="{Binding Age}" />
Posted on February 25, 2014, in Advanced, C#, DataBinding, WPF and tagged advanced, C#, C-sharp, DataBinding, GUI, programming, Source code, WPF. Bookmark the permalink. Leave a comment.
Leave a comment
Comments 0