Aplikację, którą stworzymy, oprzemy o architekturę trójwarstwową (więcej o tej architekturze można przeczytać w jednym z wcześniejszych postów z wcześniejszych postów.
Na początek potrzebujemy bazę danych. Będzie to prosta baza danych z trzema tabelami połączonymi relacjami:
Tak więc mamy już naszą bazę danych. Teraz należy stworzyć warstwę Access Layer. Tworzymy nowy projekt w obrębie naszej solucji i nadajemy mu np. nazwę DAL. Informacje nt. ConnectionString przechowamy w pliku ustawień projektu DAL:
Dzięki temu mamy łatwy dostęp do niego a w razie zmiany używanej bazy - wystarczy w jednym miejscu dokonać stosownej modyfikacji. W ustawieniach można także zapisać providera użytego do podłączenia do bazy danych.
Potrzebne są nam także klasy, odzwierciedlające tabele w bazie. W przypadku DataSetów otrzymywaliśmy je gotowe. Tym razem napiszemy je sami:
DataAccesLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Collections.ObjectModel;
using DataAccessComponents;
namespace DAL
{
public class WPFDbOperations
{
private string connectionString = Properties.Settings.Default.WPFDb;
private string dbProvider = Properties.Settings.Default.DbProvider;
public Person GetPersonById(int id)
{
Person person = new Person();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM person WHERE idPerson = @idPerson";
DbParameter parameter = provider.CreateParameter();
parameter.DbType = DbType.Int32;
parameter.ParameterName = "@idPerson";
parameter.Value = id;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
person.FirstName = (string)dr["FirstName"];
person.LastName = (string)dr["LastName"];
person.IdPerson = (int)dr["IdPerson"];
person.YearOfBirt = (int)dr["YearOfBirth"];
}
}
person.Cars = GetCarsByPerson(person.IdPerson);
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return person;
}
public ObservableCollection<Person> GetPersons()
{
ObservableCollection<Person> persons = new ObservableCollection<Person>();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM person";
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
Person person = new Person();
person.FirstName = (string)dr["FirstName"];
person.LastName = (string)dr["LastName"];
person.IdPerson = (int)dr["IdPerson"];
person.YearOfBirt = (int)dr["YearOfBirth"];
person.Cars = GetCarsByPerson(person.IdPerson);
persons.Add(person);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return persons;
}
public bool UpdatePerson(Person p)
{
Person person = p;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "UPDATE person SET firstName = @firstName, lastName = @lastName, yearOfBirth = @yearOfBirth WHERE idPerson = @idPerson";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idPerson";
parameter.Value = person.IdPerson;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@firstName";
parameter.Value = person.FirstName;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@lastName";
parameter.Value = person.LastName;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@yearOfBirth";
parameter.Value = person.YearOfBirt;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public bool DeletePerson(Person p)
{
Person person = p;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "DELETE FROM person WHERE idPerson = @idPerson";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idPerson";
parameter.Value = person.IdPerson;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public Color GetColorById(int id)
{
Color color = new Color();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM color WHERE idColor = @idColor";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idColor";
parameter.Value = id;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
color.IdColor = (int)dr["IdColor"];
color.Value = (string)dr["Value"];
color.Cars = GetCarsByColor(color.IdColor);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return color;
}
public ObservableCollection<Color> GetColors()
{
ObservableCollection<Color> colors = new ObservableCollection<Color>();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM color";
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
Color color = new Color();
color.Value = (string)dr["Value"];
color.IdColor = (int)dr["IdColor"];
colors.Add(color);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return colors;
}
public bool UpdateColor(Color c)
{
Color color = c;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "UPDATE color SET value = @value WHERE idColor = @idColor";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idColor";
parameter.Value = color.IdColor;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@value";
parameter.Value = color.Value;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public bool DeleteColor(Color c)
{
Color color = c;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "DELETE FROM color WHERE idColor = @idColor";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idColor";
parameter.Value = color.IdColor;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public Car GetCarById(int id)
{
Car car = new Car();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM car WHERE idCar = @idCar";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idCar";
parameter.Value = id;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
car.IdCar = (int)dr["IdCar"];
car.Mark = (string)dr["Mark"];
car.ProductionYear = (int)dr["ProductionYear"];
car.IdColor = (int)dr["IdColor"];
car.IdPerson = (int)dr["IdPerson"];
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return car;
}
public ObservableCollection<Car> GetCars()
{
ObservableCollection<Car> cars = new ObservableCollection<Car>();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM car";
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
Car car = new Car();
car.IdCar = (int)dr["IdCar"];
car.Mark = (string)dr["Mark"];
car.ProductionYear = (int)dr["ProductionYear"];
car.IdColor = (int)dr["IdColor"];
car.IdPerson = (int)dr["IdPerson"];
cars.Add(car);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return cars;
}
public bool UpdateCar(Car c)
{
Car car = c;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "UPDATE car SET mark = @mark, productionYear = @productionYear, idColor = @idColor, idPerson = @idPerson WHERE idCar = @idCar";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idCar";
parameter.Value = car.IdCar;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@mark";
parameter.Value = car.Mark;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@productionYear";
parameter.Value = car.ProductionYear;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@idColor";
parameter.Value = car.IdColor;
cmd.Parameters.Add(parameter);
parameter = provider.CreateParameter();
parameter.ParameterName = "@idPerson";
parameter.Value = car.IdPerson;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public bool DeleteCar(Car c)
{
Car car = c;
bool returnValue = false;
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "DELETE FROM car WHERE idCar = @idCar";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idCar";
parameter.Value = car.IdCar;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
returnValue = true;
}
conn.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
return returnValue;
}
return returnValue;
}
public ObservableCollection<Car> GetCarsByPerson(int id)
{
ObservableCollection<Car> cars = new ObservableCollection<Car>();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM car WHERE idPerson = @idPerson";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idPerson";
parameter.Value = id;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
Car car = new Car();
car.IdCar = (int)dr["IdCar"];
car.Mark = (string)dr["Mark"];
car.ProductionYear = (int)dr["ProductionYear"];
car.IdColor = (int)dr["IdColor"];
car.IdPerson = (int)dr["IdPerson"];
cars.Add(car);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return cars;
}
public ObservableCollection<Car> GetCarsByColor(int id)
{
ObservableCollection<Car> cars = new ObservableCollection<Car>();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = "SELECT * FROM car WHERE idColor = @idColor";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idColor";
parameter.Value = id;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
Car car = new Car();
car.IdCar = (int)dr["IdCar"];
car.Mark = (string)dr["Mark"];
car.ProductionYear = (int)dr["ProductionYear"];
car.IdColor = (int)dr["IdColor"];
car.IdPerson = (int)dr["IdPerson"];
cars.Add(car);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return cars;
}
public Color GetColorByCarId(int idCar)
{
Color color = new Color();
DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = provider.CreateCommand();
cmd.Connection = conn;
try
{
string sqlQuery = @"SELECT col.idColor, col.value
FROM car c join color col ON c.IdColor = col.IdColor
WHERE c.IdCar = @idCar";
DbParameter parameter = provider.CreateParameter();
parameter.ParameterName = "@idCar";
parameter.Value = idCar;
cmd.Parameters.Add(parameter);
cmd.CommandText = sqlQuery;
conn.Open();
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
color.IdColor = (int)dr["IdColor"];
color.Value = (string)dr["Value"];
color.Cars = GetCarsByColor(color.IdColor);
}
}
dr.Close();
}
catch (Exception e)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
return color;
}
}
}
Data Access Components - czyli obiekty przedstawiające tabele w bazie danych:
Car.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace DataAccessComponents
{
public class Car
{
private int _idCar;
public int IdCar
{
get { return _idCar; }
set { _idCar = value; }
}
private string _mark;
public string Mark
{
get { return _mark; }
set { _mark = value; }
}
private int _productionYear;
public int ProductionYear
{
get { return _productionYear; }
set { _productionYear = value; }
}
private int _idColor;
public int IdColor
{
get { return _idColor; }
set { _idColor = value; }
}
private int _idPerson;
public int IdPerson
{
get { return _idPerson; }
set { _idPerson = value; }
}
public Car(int idCar, int productionYear, string mark, int idColor, int idPerson)
{
_idCar = idCar;
_mark = mark;
_productionYear = productionYear;
_idCar = idColor;
_idPerson = idPerson;
}
public Car()
: this(0, 0, null, 0, 0)
{
}
}
}
Color.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace DataAccessComponents
{
public class Color
{
private int _idColor;
public int IdColor
{
get { return _idColor; }
set { _idColor = value; }
}
private string _value;
public string Value
{
get { return _value; }
set { _value = value; }
}
private ObservableCollection<Car> _cars;
public ObservableCollection<Car> Cars
{
get { return _cars; }
set { _cars = value; }
}
public Color(int idColor, string value, ObservableCollection<Car> cars)
{
_cars = cars;
_idColor = idColor;
_value = value;
}
public Color()
: this(0, null, null)
{
}
}
}
Person.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace DataAccessComponents
{
public class Person
{
private int _idPerson;
public int IdPerson
{
get { return _idPerson; }
set { _idPerson = value; }
}
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
private int _yearOfBirt;
public int YearOfBirt
{
get { return _yearOfBirt; }
set { _yearOfBirt = value; }
}
private ObservableCollection<Car> _cars;
public ObservableCollection<Car> Cars
{
get { return _cars; }
set { _cars = value; }
}
public Person(int idPerson, string firstName, string lastName, int yearOfBirt, ObservableCollection<Car> cars)
{
_idPerson = idPerson;
_firstName = firstName;
_lastName = lastName;
_yearOfBirt = yearOfBirt;
_cars = cars;
}
public Person()
: this(0, null, null, 0, null)
{
}
}
}
Business Logic Layer:
CarBL.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Collections.ObjectModel;
using DataAccessComponents;
namespace BL
{
public class CarBL
{
private WPFDbOperations dal = new WPFDbOperations();
public Car GetCarById(int idCar)
{
return dal.GetCarById(idCar);
}
public ObservableCollection<Car> GetCars()
{
return dal.GetCars();
}
public ObservableCollection<Car> GetCarsByColor(int idColor)
{
return dal.GetCarsByColor(idColor);
}
public ObservableCollection<Car> GetCarByPerson(int idPerson)
{
return dal.GetCarsByPerson(idPerson);
}
public bool DeleteCar(Car car)
{
return dal.DeleteCar(car);
}
public bool UpdateCarInformation(Car car)
{
return dal.UpdateCar(car);
}
}
}
ColorBL.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using DataAccessComponents;
using System.Collections.ObjectModel;
namespace BL
{
public class ColorBL
{
private WPFDbOperations op = new WPFDbOperations();
public ObservableCollection<Color> GetAllColors()
{
return op.GetColors();
}
public Color GetColorInformation(int idColor)
{
return op.GetColorById(idColor);
}
public bool DeleteColorById(Color color)
{
return op.DeleteColor(color);
}
public bool UpdateColorInformation(Color color)
{
return op.UpdateColor(color);
}
public Color GetCarColor(int idCar)
{
return op.GetColorByCarId(idCar);
}
}
}
PersonBL.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using DataAccessComponents;
using DAL;
namespace BL
{
public class PersonBL
{
private WPFDbOperations op = new WPFDbOperations();
public ObservableCollection<Person> GetAllPerson()
{
return op.GetPersons();
}
public Person GetPersonById(int idPerson)
{
return op.GetPersonById(idPerson);
}
public bool DeletePersonById(Person p)
{
return op.DeletePerson(p);
}
public bool UpdatePersonInformation(Person p)
{
return op.UpdatePerson(p);
}
}
}
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BL;
using DataAccessComponents;
namespace WPFDbBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void lbCars_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lbCars.SelectedIndex > -1)
{
Car car = lbCars.SelectedItem as Car;
if (car != null)
{
int idCar = car.IdCar;
ColorBL cbl = new ColorBL();
DataAccessComponents.Color color = cbl.GetCarColor(car.IdCar);
lbColors.Items.Clear();
lbColors.Items.Add(color);
}
}
}
}
}
MainWindow.xaml:
<Window x:Class="WPFDbBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:BL;assembly=BL"
xmlns:s="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ObjectDataProvider MethodName="GetAllPerson" ObjectType="{x:Type c:PersonBL}" x:Key="AllPersons" />
<DataTemplate x:Key="ColorTemplate">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Value}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="CarTemplate">
<ListBoxItem>
<ListBoxItem.Content>
<StackPanel>
<StackPanel.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStopCollection>
<GradientStop Color="LightSlateGray" Offset="0.33" />
<GradientStop Color="LightSkyBlue" Offset="0.66" />
<GradientStop Color="LightGreen" Offset="1.0" />
</GradientStopCollection>
</LinearGradientBrush>
</StackPanel.Background>
<TextBlock Text="{Binding Path=Mark}" />
<TextBlock Text="{Binding Path=ProductionYear}" />
</StackPanel>
</ListBoxItem.Content>
</ListBoxItem>
</DataTemplate>
<DataTemplate x:Key="PeopleList">
<Border BorderBrush="Blue" BorderThickness="2" CornerRadius="10" Width="{Binding ElementName=lbPerson, Path=Width}">
<Border.Background>
<LinearGradientBrush EndPoint="1,1" StartPoint="0,0">
<GradientStopCollection>
<GradientStop Offset="0.33" Color="Beige" />
<GradientStop Offset="0.66" Color="Azure" />
<GradientStop Offset="1.0" Color="BlanchedAlmond" />
</GradientStopCollection>
</LinearGradientBrush>
</Border.Background>
<StackPanel Orientation="Vertical">
<Label Content="{Binding Path=FirstName}" />
<Label Content="{Binding Path=LastName}" />
<Label Content="{Binding Path=YearOfBirt}" />
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="0.2*" />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0" Orientation="Vertical" >
<TextBlock Text="Osoby:" HorizontalAlignment="Center"/>
<ListBox SelectedIndex="0" Name="lbPerson" ItemsSource="{Binding Source={StaticResource ResourceKey=AllPersons}}" ItemTemplate="{StaticResource ResourceKey=PeopleList}"/>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="0" Orientation="Vertical">
<TextBlock Text="Pojazdy:" HorizontalAlignment="Center" />
<ListBox Name="lbCars" ItemTemplate="{StaticResource ResourceKey=CarTemplate}" ItemsSource="{Binding ElementName=lbPerson, Path=SelectedItem.Cars, Mode=OneWay}" SelectionChanged="lbCars_SelectionChanged" />
</StackPanel>
<StackPanel Grid.Column="2" Grid.Row="0" Orientation="Vertical">
<TextBlock Text="Kolor:" HorizontalAlignment="Center" />
<ListBox Name="lbColors" ItemTemplate="{StaticResource ResourceKey=ColorTemplate}" />
</StackPanel>
</Grid>
</Window>
Czylli po wprowadzeniu wszystkiego nasz Solution powinien wyglądać następująco:
Parę słów o projekcie. Podczas bindowania należy używać właściwości (najprostsze bindowanie). Jeżeli chcemy bindować do metody zwracającej rezultat w postaci obiektu czy też listy możemy skorzystać z ObjectDataProvider:
<ObjectDataProvider MethodName="GetAllPerson" ObjectType="{x:Type c:PersonBL}" x:Key="AllPersons" />
W przypadku list obiektów które bindujemy z ListBoxem warto w Resourcach tworzyć DataTemplate, który umożliwia nadanie wyglądu tworzonemu wynikowi.
Działająca aplikacja:
Dodawanie kolejnych opcji typu dodanie kolejnego samochodu czy osoby wiąże się tylko z stworzeniem odpowiednich kontrolek do wprowadzania danych, validacji oraz skorzystania z gotowych metod zawartych w Business Logic Layer (BL w projekcie).
Jak widać praca z własnymi obiektami nie jest taka trudna. W następnej części zobaczymy jak prosto bindować takie obiekty jak DataSet, LINQ oraz trochę o wydajności w przypadku pracy z dużą ilością danych.
Projekt można pobrać stąd.
Brak komentarzy:
Prześlij komentarz