strana 283
----------
C#:
using System.Collections.Generic;

namespace prvky
{
  public partial class MainPage : UserControl
  {
    public MainPage()
    {
      InitializeComponent();
      dataGrid1.ItemsSource = Zakaznik.DejSeznam();
    }
  }
}

public class Zakaznik
{
  public String Jmeno { get; set; }
  public String Prijmeni { get; set; }
  public String Adresa { get; set; }
  public Boolean JeNovy { get; set; }

  public Zakaznik(String jmeno, String prijmeni, String adresa, Boolean jenovy)
  {
    this.Jmeno = jmeno;
    this.Prijmeni = prijmeni;
    this.Adresa = adresa;
    this.JeNovy = jenovy;
  }

  public static List<Zakaznik> DejSeznam()
  {
    return new List<Zakaznik>(new Zakaznik[3] 
    {
      new Zakaznik("Jan", "Novák", "Gagarinova 54 Prievidza", false), 
      new Zakaznik("Zuzana", "Tichá", "Komjatna 1367", true),
      new Zakaznik("Emil", "Skokan", "Krížna 33 Bratislava", true),
    });
  }
}




strana 284
----------
<data:DataGrid x:Name="dataGrid1" AutoGenerateColumns="False" >
  <data:DataGrid.Columns>
    <data:DataGridTextColumn Binding="{Binding Jmeno}" Header="Jméno"/>
    <data:DataGridTextColumn Binding="{Binding Prijmeni}" Header="Příjmení" />
    <data:DataGridTextColumn Binding="{Binding Adresa}" Header="Bydliště"/>
    <data:DataGridTextColumn Binding="{Binding JeNovy}" Header="Nový zákazník"/>
  </data:DataGrid.Columns>
</data:DataGrid>


<data:DataGrid x:Name="dataGrid5" Height="125" AutoGenerateColumns="False" 
  RowBackground="Wheat"  AlternatingRowBackground="LightGoldenrodYellow">
  <data:DataGrid.Columns>
    <data:DataGridTemplateColumn Header="Jméno">
      <data:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
            <TextBlock Padding="5,0,5,0" Text="{Binding Jmeno}"/>
            <TextBlock Text="{Binding Prijmeni}"/>
          </StackPanel>
        </DataTemplate>
      </data:DataGridTemplateColumn.CellTemplate>

      <data:DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal">
            <TextBox Text="{Binding Jmeno}" BorderThickness="1"/>
            <TextBox Text="{Binding Prijmeni}" BorderThickness="1"/>
          </StackPanel>
        </DataTemplate>
      </data:DataGridTemplateColumn.CellEditingTemplate>
    </data:DataGridTemplateColumn>
    <data:DataGridTextColumn
      Header="Adresa" Width="300"  Binding="{Binding Adresa}" />
  </data:DataGrid.Columns>
</data:DataGrid>



strana 285
----------
<data:DataGrid x:Name="dataGrid1" AutoGenerateColumns="False"
  RowDetailsVisibilityMode="VisibleWhenSelected" > 
  <data:DataGrid.Columns>
    <data:DataGridTextColumn Binding="{Binding Jmeno}" Header="Jméno"/>
    <data:DataGridTextColumn Binding="{Binding Prijmeni}" Header="Příjmení" />
  </data:DataGrid.Columns>

  <data:DataGrid.RowDetailsTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock FontSize="12" Text="Adresa: " />
        <TextBlock FontSize="12" Text="{Binding Adresa}"/>
      </StackPanel>
    </DataTemplate>
  </data:DataGrid.RowDetailsTemplate>
</data:DataGrid>



strana 286
----------
C#:
public class Zakaznik
{
  public String Jmeno { get; set; }
  public String Prijmeni { get; set; }
  public String Pohlavi { get; set; }
  public String VekSkupina { get; set; }


  public Zakaznik(String jmeno, String prijmeni, String pohlavi, String vekskupina)
  {
    this.Jmeno = jmeno;
    this.Prijmeni = prijmeni;
    this.Pohlavi = pohlavi;
    this.VekSkupina = vekskupina;
  }

  public static List<Zakaznik> DajSeznam()
  {
    return new List<Zakaznik>(new Zakaznik[5] 
    {
      new Zakaznik("Jan", "Novák", "M", "Dospělý"), 
      new Zakaznik("Zuzana", "Tichá", "Z", "Teenager"),
      new Zakaznik("Emil", "Skokan", "M", "Teenager"),
      new Zakaznik("Elena", "Kalivodová", "Z", "Teenager"),
      new Zakaznik("František", "Tichý", "M", "Dospělý"),
    });
  }
}


strana 287
----------
<Grid x:Name="LayoutRoot" Background="White">
  <StackPanel>
    <StackPanel Orientation="Horizontal">
      <TextBlock Text="Zaskupit:" Margin="0,0,10,0" /> 
      <ComboBox x:Name="Skupiny" SelectionChanged="Skupiny_SelectionChanged">
        <ComboBox.Items>
          <ComboBoxItem Content="VekSkupina" IsSelected="True" /> 
          <ComboBoxItem Content="Pohlavi" /> 
        </ComboBox.Items> 
      </ComboBox> 
    </StackPanel> 
    <data:DataGrid x:Name="dataGrid1" /> 
  </StackPanel>
</Grid>



strana 288
----------
C#:
PagedCollectionView pcv = null;
bool bPrvniZmena = true;

public MainPage()
{
  InitializeComponent();
  dataGrid1.ItemsSource = null;
  pcv = new PagedCollectionView(Zakaznik.DejSeznam());
  pcv.GroupDescriptions.Add(new PropertyGroupDescription("VekSkupina"));
  dataGrid1.ItemsSource = pcv;  
}


private void Skupiny_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  if (bPrvniZmena) bPrvniZmena = false;
  else
  {
    ComboBoxItem osoba = ((sender as ComboBox).SelectedItem as ComboBoxItem);
    pcv.GroupDescriptions.Clear();
    pcv.GroupDescriptions.Add(new
    PropertyGroupDescription(osoba.Content.ToString()));
    dataGrid1.ItemsSource = null;
    dataGrid1.ItemsSource = pcv;
  }
}




private void ExpandButton_Click(object sender, RoutedEventArgs e)
{
  PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
  try
  {
    foreach (CollectionViewGroup group in pcv.Groups)
    {
      dataGrid1.ExpandRowGroup(group, true);
    }
  }
  catch (Exception ex){MessageBox.Show(ex.Message); }
}

private void CollapseButton_Click(object sender, RoutedEventArgs e)
{
  PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
  try
  {
    foreach (CollectionViewGroup group in pcv.Groups)
    {
      dataGrid1.ScrollIntoView(group, null);
      dataGrid1.CollapseRowGroup(group, true);
    }
  }
  catch (Exception ex){MessageBox.Show(ex.Message);}
}


strana 289
----------
<Grid x:Name="LayoutRoot" Background="White">
  <StackPanel>
    <StackPanel Orientation="Horizontal">
      <TextBlock Text="Třídit:" Margin="0,0,10,0" /> 
      <ComboBox x:Name="Skupiny" SelectionChanged="Skupiny_SelectionChanged">
        <ComboBox.Items>
          <ComboBoxItem Content="Jmeno" IsSelected="True" /> 
          <ComboBoxItem Content="Prijmeni" />
          <ComboBoxItem Content="Pohlavi" />
        </ComboBox.Items> 
      </ComboBox> 
    </StackPanel> 
    <data:DataGrid x:Name="dataGrid1" /> 

C#:
PagedCollectionView pcv = null;
bool bPrvniZmena = true;

public MainPage()
{
  InitializeComponent();
  dataGrid1.ItemsSource = null;
  pcv = new PagedCollectionView(Zakaznik.DejSeznam());
  pcv.SortDescriptions.Add(new SortDescription("Jmeno", 
  ListSortDirection.Ascending));
  dataGrid1.ItemsSource = pcv;  
}

private void Skupiny_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  if (bPrvniZmena) bPrvniZmena = false;
  else
  {
    ComboBoxItem osoba = ((sender as ComboBox).SelectedItem as ComboBoxItem);
    pcv.SortDescriptions.Clear();
    pcv.SortDescriptions.Add(new SortDescription(osoba.Content.ToString(), 
    ListSortDirection.Ascending));
    dataGrid1.ItemsSource = null;
    dataGrid1.ItemsSource = pcv;
  }
}


strana 291
----------
<Grid x:Name="LayoutRoot" Background="White">
  <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition Height="30" />
  </Grid.RowDefinitions>
  <data:DataGrid x:Name="dataGrid1"  />
  <StackPanel Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Center">
    <TextBlock Text="Noví zákazníci " />
    <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
  </StackPanel>
</Grid>


C#:
public class Zakaznik
{
  public String Jmeno { get; set; }
  public String Adresa { get; set; }
  public bool Novy { get; set; }
}


public MainPage()
{
  InitializeComponent();

  // Vytvoření a naplnění seznamu údajů
  List<Zakaznik> lZakaznici = new List<Zakaznik>();
  lZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Novák Jan",
    Adresa = "Jindřišská 111, Praha 1", 
    Novy = true 
  });

  lZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Tichá Zuzana",
    Adresa = "Mierová 14, Bratislava",
    Novy = false
  });

  lZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Skokan Emil",
    Adresa = "Kostolná 334, Trnava",
    Novy = false
  });

  PagedCollectionView pcv = new PagedCollectionView(lZakaznici);
  this.dataGrid1.ItemsSource = pcv;
}


public bool FilterNovyZakaznik(object z)
{
  Zakaznik zak = z as Zakaznik;
  return (zak.Novy == true);
}


private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
  PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
  if (pcv != null && pcv.CanFilter == true)
  {
    pcv.Filter = new Predicate<object>(FilterNovyZakaznik);
  }
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
  PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
  if (pcv != null)
  {
    pcv.Filter = null;
  }
}



strana 293
----------
C#:
public enum Stav
{ 
  STUJ,
  PRIPRAV,
  JED
}



using System.ComponentModel;
using System.Windows.Data;

public class Svetla : INotifyPropertyChanged
{
  public Stav St
  {
    get { return (st); }
    set 
    { 
      st = value;
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs("St"));
      }
    }
  }

  private Stav st;
  public event PropertyChangedEventHandler PropertyChanged;
}



strana 294
----------
C#:
public partial class Page : UserControl
{
  public Page()
  {
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(Page_Loaded);
  }

  void Page_Loaded(object sender, RoutedEventArgs e)
  {
    LayoutRoot.DataContext = new Svetla()
    { St = Stav.STUJ; };
  }
}



public class Konverze : IValueConverter
{

  public object Convert(object value, Type targetType, object parameter, 
    System.Globalization.CultureInfo culture)
  {
    Stav st = (Stav)value;
    SolidColorBrush brush = new SolidColorBrush(Colors.Red);
    switch (st)
    {
      case Stav.STUJ:
        break;
      case Stav.PRIPRAV:
        brush = new SolidColorBrush(Colors.Orange);
        break;
      case Stav.JED:
        brush = new SolidColorBrush(Colors.Green);
        break;
      default:
        break;
    }
    return (brush);
  }

  public object ConvertBack(object value, Type targetType, object parameter, 
    System.Globalization.CultureInfo culture)
  {
    return (null);
  }
}



strana 295
----------
<UserControl x:Class="Semafor.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:me="clr-namespace:Semafor" 
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="400">

  <UserControl.Resources>
    <me:Konverze x:Key="konv">
    </me:Konverze>
  </UserControl.Resources>

  <Grid x:Name="LayoutRoot" Background="White">

  </Grid>
</UserControl>



strana 296
----------
<Grid x:Name="LayoutRoot" Background="White">
  <StackPanel  Background="White" Orientation="Vertical">
    <my:DataGrid AutoGenerateColumns="True" ColumnWidth="*" x:Name="dgMesta" 
      ItemsSource="{Binding Path=Mesta}"></my:DataGrid>
    <StackPanel Margin="5" Orientation="Horizontal">
      <Button Content="ADD" x:Name="btAdd" Margin="5" Width="120" 
        Click="btAdd_Click" />
      <Button Content="DEL" x:Name="btDel" Margin="5" Width="120" 
        Click="btDel_Click" />
      <Button Content="CLEAR" x:Name="btClear"   Margin="5" Width="120" 
        Click="btClear_Click" />
    </StackPanel>
  </StackPanel>
</Grid>


C#:
public class cPoloha
{
  public string sNazev { get; set; }
  public double dLatitude { get; set; }
  public double dLongitude { get; set; }

  public cPoloha(string nazev, double latitude, double longitude)
  {
    sNazev = nazev;
    dLatitude = latitude;
    dLongitude = longitude;
  }
}


public MainPage()
{
  InitializeComponent();
  InicializaceDat(Mesta);
  this.DataContext = this;
}

private void InicializaceDat(Lokality _lokality)
{
  _lokality.Add(new cPoloha("Brezno", 48.805172, 19.638518));
  _lokality.Add(new cPoloha("Ružomberok", 49.073327, 19.317253));
  _lokality.Add(new cPoloha("Handlová", 48.726635, 18.767438));
  _lokality.Add(new cPoloha("Žiar nad Hronom", 48.589838, 18.864314));
  _lokality.Add(new cPoloha("Detva", 48.564213, 19.421374));
  _lokality.Add(new cPoloha("Tisovec", 48.680959, 19.941835));
}



strana 298
----------
C#:
private void btAdd_Click(object sender, RoutedEventArgs e)
{
  // vytvoření nového záznamu
  cPoloha noveMesto = new cPoloha("<Nove>", 0,0);
  Mesta.Add(noveMesto);

  // vyber nového záznamu a jeho otevření pro editování
  dgMesta.SelectedItem = noveMesto;
  dgMesta.Focus();
  dgMesta.BeginEdit();

}


private void btDel_Click(object sender, RoutedEventArgs e)
{
  if (dgMesta.SelectedItem != null && dgMesta.SelectedItem is cPoloha)
    Mesta.Remove((cPoloha)dgMesta.SelectedItem);
  else
   MessageBox.Show("Nejprve musíte vybrat záznam, který chcete vymazat");
}

private void btClear_Click(object sender, RoutedEventArgs e)
{
  Mesta.Clear();
}




strana 300
----------
C#:
public class Zakaznik : System.ComponentModel.INotifyPropertyChanged, 
  IEditableObject
{
  //privátní atributy
  private string mJmeno = string.Empty;
  private string mAdresa = string.Empty;
  private bool mNovy = false;

  //proměnné pro stornování editování
  private Zakaznik tTask = null;
  private bool bEditovane = false;


//veřejné atributy

[Display(Name = "Jméno")]
public string Jmeno
{
  get { return this.mJmeno; }
  set
  {
    if (value != this.mJmeno)
    {
      this.mJmeno = value; NotifyPropertyChanged("Jmeno");
    }
  }
}

[Display(Name = "Adresa")]
public string Adresa
{
  get { return this.mAdresa; }
  set
  {
    if (value != this.mAdresa)
    {
      this.mAdresa = value; NotifyPropertyChanged("Adresa");
    }
  }
}

[Display(Name = "Nový zákazník")]
public bool Novy
{
  get { return this.mNovy; }
  set
  {
    if (value != this.mNovy)
    {
      this.mNovy = value;  NotifyPropertyChanged("Novy");
    }
  }
}


// Implementace rozhraní INotifyPropertyChanged 
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string propertyName)
{
  if (PropertyChanged != null)
  {
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

// Implementace rozhraní IEditableObject
public void BeginEdit()
{
  if (bEditovane == false)
  {
    tTask = this.MemberwiseClone() as Zakaznik;
    bEditovane = true;
  }
}

public void CancelEdit()
{
  if (bEditovane == true)
  {
    this.Jmeno = tTask.Jmeno;
    this.Adresa = tTask.Adresa;
    this.Novy = tTask.Novy;
  }
}

public void EndEdit()
{
  if (bEditovane == true)
  {
    tTask = null;
    bEditovane = false;
  }
}




strana 301
----------
C#:
public MainPage()
{
  InitializeComponent();

  // Vytvoření a naplnění seznamu údajů
  ObservableCollection<Zakaznik> ocZakaznici = new ObservableCollection<Zakaznik>();
  ocZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Novák Jan", Adresa = "Jindřišská 111, Praha 1", Novy = true
  });

  ocZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Tichá Zuzana", Adresa = "Mierová 14, Bratislava", Novy = false
  });

  ocZakaznici.Add(new Zakaznik()
  {
    Jmeno = "Skokan Emil", Adresa = "Kostolná 334, Trnava",  Novy = false
  });

  dataGrid1.ItemsSource = ocZakaznici;
}


strana 302
----------
<my:DataGrid AutoGenerateColumns="False" 
  x:Name="dataGrid2" HeadersVisibility="All">
  <my:DataGrid.Columns>
    <my:DataGridTextColumn Header="Jmeno" 
      Binding="{Binding jmeno}" Width="*"/>
    <my:DataGridTextColumn Header="Adresa" 
      Binding="{Binding adresa}" Width="2*"/>
    <my:DataGridTextColumn Header="Mesto" 
      Binding="{Binding mesto}" Width="100"/>
    <my:DataGridTextColumn Header="Stat" 
      Binding="{Binding stat}" Width="50" />
    <my:DataGridTextColumn Header="PSC" 
      Binding="{Binding psc}"  Width="80"/>
  </my:DataGrid.Columns>
</my:DataGrid>


C#:
public partial class MainPage : UserControl
{

  public MainPage()
  {
    InitializeComponent();
    dataGrid2.ItemsSource = Kontakty.DajSeznam(); 
  }
}

public class Kontakty 
{
  public String jmeno { get; set; }
  public String adresa { get; set; }
  public String mesto { get; set; }
  public String stat { get; set; }
  public String psc { get; set; }
}

  public Kontakty(String Jmeno, String Adresa, String Mesto, 
    String Stat, String Psc)
  {
    jmeno = Jmeno;
    adresa = Adresa;
    mesto = Mesto;
    stat = Stat;
    psc = Psc;
   }

  public static List<Kontakty> DajSeznam()
  {
    return new List<Kontakty>(new Kontakty[3] 
    {
      new Kontakty("Churavý Jozef", "Mýtna 14", 
        "Ružomberok", "SK",  "03401"), 
      new Kontakty("Galambošová Erika", "Poštová 19", 
        "Liptovská Teplá", "SK", "03483"),
      new Kontakty("Chocholoušek Tibor", "Rovná 9", 
        "Liptovský Mikuláš", "SK", "03101")
      });
    }
  }




strana 304
----------
<StackPanel x:Name="LayoutRoot" Background="White"> 
  <TextBox Margin="15" Width="200" 
    Text="{Binding Meno,Mode=TwoWay,ValidatesOnExceptions=True}" /> 
  <TextBox Margin="15" Width="200" 
    Text="{Binding OsCislo,Mode=TwoWay,ValidatesOnExceptions=True}"/> 
  <ListBox x:Name="lstErrors"  ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <TextBlock Text="{Binding Exception.Message}" />
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
  <Button Width="200" Content="Potvrd" Click="Button_Click"  />
</StackPanel>


C#:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SL3new
{
  public partial class MainControl : UserControl
  {
    public MainControl()
    {
      // Required to initialize variables
      InitializeComponent();
      this.Loaded += OnLoaded;
    }

    void OnLoaded(object sender, RoutedEventArgs e)
    {
      this.DataContext = new Pracovnik("Jozef Novak", 100);
      lstErrors.DataContext = this;
    }

    private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
      List<ValidationError> errors = new List<ValidationError>();

      foreach (UIElement ui in LayoutRoot.Children)
      {
        FrameworkElement fe = ui as FrameworkElement;

        if (fe != null)
        {
          foreach (ValidationError ve in Validation.GetErrors(fe))
          {
            errors.Add(ve);
          }
        }
      }
      lstErrors.DataContext = errors;
    }
  }

  public class InvalidDataException : Exception
  {
    public InvalidDataException(string msg) : base(msg)
    {
    }
  }
}



strana 306
----------
C#:
public class Pracovnik 
{
  string jmeno;
  int osCislo;

  public Pracovnik(string jmeno, int osCislo)
  {
    this.jmeno = jmeno;
    this.osCislo = osCislo;
  }

  public string Jmeno
  {
    get {return (jmeno);}
    set {KontrolaDelky(value, 3, 15); jmeno = value;}
  }

  public int OsCislo
  {
    get { return (osCislo); }
    set
    {
      if ((value < 100) || (value > 199))
      {
        throw new InvalidDataException("Neplatné osobní číslo");
      }
      osCislo = value;
    }
  }
)


strana 309
----------
C#:
public class Produkt : INotifyPropertyChanged, IDataErrorInfo
{

  private string _Nazev;
  public string Nazev
  {
    get { return _Nazev; }
    set { _Nazev = value; NotifyPropertyChanged("Nazev"); }
  }

  private string _Kod;
  public string Kod
  {
    get { return _Kod; }
    set { _Kod = value; NotifyPropertyChanged("Kod"); }
  }

  private float _Cena;
  public float Cena
  {
    get { return _Cena; }
    set { _Cena = value; NotifyPropertyChanged("Cena"); }
  }

  private float _Provize;
  public float Provize
  {
    get { return _Provize; }
    set { _Provize = value; NotifyPropertyChanged("Provize"); }
  }

  protected void NotifyPropertyChanged(string PropertyName)
  {
  if (null != PropertyChanged)
    PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
  }

  public event PropertyChangedEventHandler PropertyChanged;

  string errors = null;
  public string Error
  {
    get { return errors; }
  }

  public string this[string sloupec]
  {
    get
    {
      string oznam = null;

      if (sloupec == "Nazev")
      {
        if (String.IsNullOrEmpty(Nazev))
          oznam = "Název musí být zadaný!";
        else if (Nazev.Length < 3)
          oznam = "Název musí mít délku alespoň 3 znaky!";
      }

      else if (sloupec == "Kod")
      {
        if (null != Kod)
        if (Kod.Length < 3 || Kod.Length > 5)
          oznam = "Neplatný kód!";
      }

      else if (sloupec == "Cena")
      {
      if (Cena <= 0)
        oznam = "Cena musí být kladné číslo!";
      }
      else if (sloupec == "Provize")
      {
        if (Provize <= 0)
          oznam = "Cena musí být kladné číslo!";
        else if (Provize >= 1) Provize /= 100;
      }
      return oznam;
    }
  }
}


strana 311
----------
<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:DgValidace">

  <Style x:Key="tb" TargetType="TextBlock">
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="Margin" Value="3"/>
  </Style>

  <Style TargetType="local:Formular">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="local:Formular">
          <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            CornerRadius="3" Width="{TemplateBinding Width}">
            <Grid>
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition Width="*"/>
              </Grid.ColumnDefinitions>

              <TextBlock Grid.Column="0" Grid.Row="0" Text="Nazev:"/>
              <TextBox Grid.Column="1" Grid.Row="0" x:Name="txtNazev"
                Text="{Binding Path=fProdukt.Nazev, Mode=TwoWay, 
                ValidatesOnDataErrors=True}"/>

              <TextBlock Grid.Column="0" Grid.Row="1" Text="Kod:" />
              <TextBox Grid.Column="1" Grid.Row="1"   x:Name="txtKod"
                Text="{Binding Path=fProdukt.Kod, Mode=TwoWay, 
                ValidatesOnDataErrors=True}"/>

              <TextBlock Grid.Column="0" Grid.Row="2" Text="Cena:" />
              <TextBox Grid.Column="1" Grid.Row="2" x:Name="txtCena"
                Text="{Binding Path=fProdukt.Cena,	Mode=TwoWay, 
                ValidatesOnDataErrors=True}"/>

              <TextBlock Grid.Column="0" Grid.Row="3" Text="Provize:"/>
              <TextBox Grid.Column="1" Grid.Row="3" 	x:Name="txtProvize"
                Text="{Binding Path=fProdukt.Provize, Mode=TwoWay, 
                ValidatesOnDataErrors=True}" />
            </Grid>
          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>



strana 312
----------
C#:
public class Formular : Control
{
  public Formular()
  {
    this.DefaultStyleKey = typeof(Formular);
    this.DataContext = this;
  }

  public bool IsLocked
  {
    get { return (bool)GetValue(propIsLocked); }
    set { SetValue(propIsLocked, value); }
  }

  public static readonly DependencyProperty propIsLocked =
    DependencyProperty.Register("IsLocked", typeof(bool), 
    typeof(Formular), null);

  public bool IsValid
  {
    get { return !HasBindingErrors(); }
  }

  public Produkt fProdukt
  {
    get { return (Produkt)GetValue(propProdukt); }
    set { SetValue(propProdukt, value); }
  }

  public static readonly DependencyProperty propProdukt =
    DependencyProperty.Register("fProdukt", typeof(Produkt), 
    typeof(Formular), null);

  private bool HasBindingErrors()
  {
    bool chyba = false;
    chyba |= Validation.GetHasError(GetTemplateChild("txtNazev"));
    chyba |= Validation.GetHasError(GetTemplateChild("txtKod"));
    chyba |= Validation.GetHasError(GetTemplateChild("txtCena"));
    chyba |= Validation.GetHasError(GetTemplateChild("txtProvize"));
    return chyba;
  }
}



strana 313
----------
<Grid x:Name="LayoutRoot" Background="White">

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="200"/>
    <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>

  <data:DataGrid x:Name="dg" ItemsSource="{Binding}"
    Margin="3" IsReadOnly="True"
    AutoGenerateColumns="False" 
    HeadersVisibility="Column"
    Grid.Row="0" Grid.Column="0"
    SelectionChanged="dg_SelectionChanged">
    <data:DataGrid.Columns>
      <data:DataGridTextColumn Binding="{Binding Nazev}" 
        Header="Název produktu" />
      </data:DataGrid.Columns>
    </data:DataGrid>

    <my:Formular x:Name="edf" Margin="3" Width="250" 
      HorizontalAlignment="Left" Grid.Column="1" 
      fProdukt="{Binding Path=SelectedItem, ElementName=dg}"
      sLocked="True" BorderBrush="Blue" BorderThickness="3"/>

    <StackPanel Orientation="Horizontal" Margin="3" Grid.Row="1">
      <Button Content="Nový" x:Name="btnNew" Click="btnNew_Click"/>
      <Button Content="Úprava" x:Name="btnUpdate" 
        Click="btnUpdate_Click"/>
      <Button Content="Vymazat" x:Name="btnDelete" 
        Click="btnDelete_Click"/>
    </StackPanel>
  </Grid>



strana 314
----------
C#:
public ObservableCollection<Produkt> ocProdukty { get; set; }

public MainPage()
{
  InitializeComponent();
  ocProdukty = new ObservableCollection<Produkt>();
  FillData();
  dg.ItemsSource = ocProdukty;
}

private void FillData()
{
  ocProdukty.Add(new Produkt()
  {
    Nazev = "Pouzdro", Kod = "PR12", Cena  = 50.00f, Provize = 0.08f,
  });

  ocProdukty.Add(new Produkt()
  {
    Nazev = "Housle", Kod = "QT32", Cena  = 9000.00f, Provize = 0.07f,
  });

  ocProdukty.Add(new Produkt()
  {
    Nazev = "Kytara", Kod = "GF74", Cena  = 4000.00f, Provize = 0.09f,
  });
}

private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  edf.IsLocked = true;
}

private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
  edf.IsLocked = false;
}

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
  ocProdukty.Remove(dg.SelectedItem as Produkt);
}

private void btnNew_Click(object sender, RoutedEventArgs e)
{
  Novy cw = new Novy();
  Formular formular = new Formular();
  formular.Margin = new Thickness(3);
  formular.Width = 450;
  formular.fProdukt = new Produkt();
  formular.IsLocked = false;

  cw.LayoutRoot.Children.Add(formular);
  cw.HasCloseButton = false;
  cw.Title = "Údaje o produktu";
  cw.Closed += (s, args) =>
  {
    if (cw.DialogResult.Value && formular.IsValid)
    {
      ocProdukty.Add(formular.fProdukt);
    }
  };
  cw.Closing += (s, args) =>
  {
    if (!formular.IsValid && cw.DialogResult.Value)
    {
      MessageBox.Show("Některá položka je neplatná.
        \nOpravte hodnoty v červeně orámovaných polích");
        args.Cancel = true;
    }
  };
  cw.Show();

}



strana 320
----------
XML:
<?xml version="1.0" encoding="utf-8"?>
<knihy>
  <kniha>
    <autor>Rowlling J.K.</autor>
    <titul>Harry Potter a tajemná komnata</titul>
    <cena>249</cena>
  </kniha>
  <kniha>
    <autor> Rowlling J.K.</autor>
    <titul> Harry Potter a kámen mudrců</titul>
    <cena>299</cena>
  </kniha>
  <kniha>
    <autor> Rowlling J.K.</autor>
    <titul>Harry Potter a princ dvojí krve</titul>
    <cena>399</cena>
  </kniha>
</knihy> 


<Grid x:Name="LayoutRoot" Background="White">
  <data:DataGrid Name="dataGrid1" />
</Grid> 


C#:
public class Kniha
{
  public string Autor { get; set; }
  public string Titul { get; set; }
  public double Cena { get; set; }
}


public MainPage()
{
  InitializeComponent();

  XDocument xd = XDocument.Load("knihy.xml");
  List<Kniha> ZoznamKnih = (from k in xd.Descendants("kniha")
    select new Kniha()
  {
    Autor = k.Element("autor").Value,
    Titul = k.Element("titul").Value,
    Cena = Double.Parse(k.Element("cena").Value)
  }).ToList();
  dataGrid1.ItemsSource = ZoznamKnih;
}





strana 322
----------
XDocument xd = XDocument.Load("knihy.xml");
List<Kniha> SeznamKnih = (from k in xd.Descendants("kniha")
  select new Kniha()
{
  Autor = DejElement(k.Element("autor")),
  Titul = DejElement(k.Element("titul")),
  Cena = Double.Parse(DejElement(k.Element("cena")))
}).ToList();
dataGrid1.ItemsSource = SeznamKnih;



strana 325
----------
C#:
public class Pocasi
{

  public string City { get; set; }
  public string Sunrise { get; set; }
  public string Sunset { get; set; }
  public string Humidity { get; set; }
  public string Pressure { get; set; }
  public string Condition{ get; set; }
}



public MainPage()
{
  InitializeComponent();

  XDocument xd = XDocument.Load("Weather.xml");

  List<Pocasi> pocasiCity = (from c in xd.Descendants("channel")
    select new Pocasi()
  {
    City = c.Element((XName)(yweather + "location")).
      Attribute("city").Value,
    Sunrise = c.Element((XName)(yweather + "astronomy")).
      Attribute("sunrise").Value,
    Sunset = c.Element((XName)(yweather + "astronomy")).
      Attribute("sunset").Value,
    Humidity = c.Element((XName)(yweather + "atmosphere")).
      Attribute("humidity").Value,
    Pressure = c.Element((XName)(yweather + "atmosphere")).
      Attribute("pressure").Value,
      Condition = c.Element("item").Element((XName)(yweather + "condition")).
      Attribute("text").Value,
  }).ToList();
  dataGrid1.ItemsSource = pocasiCity;
}




strana 326
----------
C#:
XNamespace yweather = "http://xml.weather.yahoo.com/ns/rss/1.0";
XNamespace geo = "http://www.w3.org/2003/01/geo/wgs84_pos#";

public MainPage()
{
  InitializeComponent();

  WebClient wc = new WebClient();
  wc.OpenReadCompleted += wc_OpenReadCompleted;
  wc.OpenReadAsync(new 
    Uri("http://weather.yahooapis.com/forecastrss?p=EZXX0012&u=c"));
}

private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  if (e.Error != null)
  {
    MessageBox.Show(e.Error.Message);
    return;
  }
  using (Stream s = e.Result)
  {

    XDocument xd = XDocument.Load(s);

    List<Pocasi> pocasiCity = (from c in xd.Descendants("channel")
      select new Pocasi()
    {
      City = c.Element((XName)(yweather + "location")).
        Attribute("city").Value,
      Sunrise = c.Element((XName)(yweather + "astronomy")).
        Attribute("sunrise").Value,
      Sunset = c.Element((XName)(yweather + "astronomy")).
        Attribute("sunset").Value,
      Humidity = c.Element((XName)(yweather + "atmosphere")).
        Attribute("humidity").Value,
      Pressure = c.Element((XName)(yweather + "atmosphere")).
        Attribute("pressure").Value,
      Condition = c.Element("item").Element((XName)(yweather + 
        "condition")).Attribute("text").Value,
    }).ToList();
    dataGrid1.ItemsSource = pocasiCity;
  }
}



strana 330
----------
C#:
[WebMethod]
public double DejKurzNakup(string sMena)
{
  switch (sMena)
  {
    case "USD": return 1.3966; 
    case "JPY": return 126.15; 
    case "GBP": return 0.86655; 
    case "CZK": return 26.223;
    case "HUF": return 271.15;
    default: return 1.0; 
  }
}


strana 332
----------
<Grid x:Name="LayoutRoot" Background="White">
  <Canvas>
    <TextBlock Text="Mena:" Canvas.Left="10" Canvas.Top="12">
    </TextBlock>
    <TextBox x:Name="tbMena" Width="75" Height="22" 
      Canvas.Left="55" Canvas.Top="10"></TextBox>
    <Button Content="Dotaz na webovou službu" Canvas.Top="9" 
      Canvas.Left="140" Click="Button_Click"></Button>
    <TextBlock x:Name="lblOznam" Canvas.Left="300" Canvas.Top="10" 
      Text="Stav: ----"></TextBlock>
    <TextBlock x:Name="lblKurz" Foreground="Blue" 
      Canvas.Left="10" Canvas.Top="35" Text="Kurz:"></TextBlock>
  </Canvas>
</Grid>


C#:
private void Button_Click(object sender, RoutedEventArgs e)
{
  WSKurzy.WSKurzySoapClient ws = new WSKurzy.WSKurzySoapClient();
  ws.DejKurzNakupCompleted += new 
  EventHandler<WSKurzy.DejKurzNakupCompletedEventArgs>(ws_Completed);
  ws.DejKurzNakupAsync(tbMena.Text.Trim());
  lblOznam.Text = "Stav: Čekám ...";
}

private void ws_Completed(object sender, 
  WSKurzy.DejKurzNakupCompletedEventArgs e)
{
  lblKurz.Text = e.Result.ToString();
  lblOznam.Text = "Stav: Hotovo ...";
}


strana 343
----------
C#:
public MainPage()
{
  InitializeComponent();
  Loaded += new RoutedEventHandler(Page_Loaded);

}

void Page_Loaded( object sender, RoutedEventArgs e )
{
  ServiceReference1.CustomerWebServiceClient ws = 
    new ServiceReference1.CustomerWebServiceClient();
  ws.GetCustomersCompleted += 
    new EventHandler<ServiceReference1.GetCustomersCompletedEventArgs> 
    (ws_GetCustomersCompleted);
  ws.GetCustomersAsync();
}

void ws_GetCustomersCompleted(object sender, 
  ServiceReference1.GetCustomersCompletedEventArgs e)
{
  dataGrid1.ItemsSource = e.Result;
}


