Con este post, vamos a mejorar nuestro aprendizaje sobre el diseño de software MVVM (Model View ViewModel) en las que claramente separamos el código por capas en el mismo ensamblado o en varios, pero en este caso lo haremos en el mismo. Para el ejemplo se me ha ocurrido mostrar la tabla periódica, en la cual no vamos a realizar modificaciones, puesto que los datos son los que son y lo único que nos interesa de ella es mostrarla correctamente.
tabla03
Como ya he comentado en otros posts, esto nos va a permitir diseñar y desarrollar un software mucho más robusto y fácil de mantener.
Las aplicaciones MVVM, son sucesoras de las aplicaciones MVC (Model View Controller). En una aplicación MVC podemos apreciar tres tipos de objetos:
Modelo
Esta capa, es la que se encarga de trabajar con los datos y contiene la capa de negocio.
Vista
La vista es la representación de cara al usuario o el objeto responsable de mostrar y permitir la interacción el usuario sobre los datos
Controlador
Permite transferir los datos desde el modelo a la vistaEsto nos permite poder sustituir o modificar cualquiera de las capas sin afectar o afectando lo menos posible al resto de capas, pudiendo mantener de un modo más eficaz nuestra aplicación. La diferencia con las aplicaciones WPF (o Silverlight) es que la capa ViewModel o modelo-vista es la responsable de exponer los datos del modelo usando bindings y de controlar el comportamiento de la vista

En nuestro caso, usamos como datos un archivo XML que he convertido a este formato desde una hoja de cálculo que tenía con los elementos de la tabla periódica y sus propiedades, como modelo, un gestor de datos desde XML, como vista la tabla periódica en XAML y como ViewModel, cada uno de los elementos de la tabla y la tabla en sí.

Los datos xml están distribuidos mediante un elemento raíz elements y como nodos hijos element los cuales contienen las propiedades en bruto que usará el ViewModel.

<elements xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <element>
    <simbolo>H</simbolo>
    <elemento>Hidrogeno</elemento>
    <numeroAtomico>1</numeroAtomico>
    <pesoAtomico>1,0079</pesoAtomico>
    <densidad>0,071</densidad>
    <valencia>1</valencia>
    <puntoEbullicion>-252,7</puntoEbullicion>
    <puntoFusion>259,2</puntoFusion>
    <estado>Gas</estado>
    <serieQuimica>Otros no metales</serieQuimica>
    <grupo>1</grupo>
    <periodo>1</periodo>
  </element>
  ...
</elements>

Los datos xml son extraídos y pasados a la clase ViewModel mediante la clase XMLManager. Esta clase extrae los datos del archivo XML y al mismo tiempo los convierte en el objeto de la clase ViewModel mediante XML.Linq. Fijaros en la línea subrayada donde desde Linq se crea el nuevo objeto Element por cada una de los componentes del archivo xml y que posteriormente la query se añade a la lista de retorno.

        public List GetElements()
        {
            string path = GetPathXML();
            List elements = new List();

            XDocument xdoc = XDocument.Load(path);

            var query = from u in xdoc.Descendants("element")
                        select new Element
                        {
                            Symbol = u.Element("simbolo").Value,
                            Name = u.Element("elemento").Value,
                            AtomicNumber = Convert.ToInt32(u.Element("numeroAtomico").Value),
                            AtomicMass = Convert.ToDouble(u.Element("pesoAtomico").Value),
                            Density = Convert.ToDouble(u.Element("densidad").Value),
                            Valencia = u.Element("valencia").Value,
                            MeltingPoint = !string.IsNullOrEmpty(u.Element("puntoEbullicion").Value) ? Convert.ToDouble(u.Element("puntoEbullicion").Value): 0,
                            BoilingPoint = !string.IsNullOrEmpty(u.Element("puntoFusion").Value) ? Convert.ToDouble(u.Element("puntoFusion").Value):0,
                            StandarState = u.Element("estado").Value,
                            SerialChemical = u.Element("serieQuimica").Value,
                            Group = Convert.ToInt32(u.Element("grupo").Value),
                            Period = Convert.ToInt32(u.Element("periodo").Value)
                        };

            elements.AddRange(query.ToList());
            return elements;
        }

Como clases ViewModel tenemos por una parte la clase Element que ostenta la entidad de cualquier elemento de la tabla y la clase PeriodicTable que alberga las colecciones. Con extremada sencillez, solo propiedades, sin métodos, de hecho no tenemos que usar la actualización de la propiedades mediante el evento PropertyChanged, ya que las propiedades de los elementos solo se van a cargar una sola vez.

Clase Element

/* ****************************************************************
* © JOAQUIN MARTINEZ RUS 2016
* PROYECTO:        Tabla periódica
* Archivo:         Element.cs
* Descripción:     Clase element.
 *
* Historial:       1. 12 sep 2016. Creación
*
* Comentarios:      Elemento de la tabla periódica
*
*
*******************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace DimitriMendeleyev
{
    public class Element: INotifyPropertyChanged
    {
        public string Symbol { get; set; }
        public string Name { get; set; }
        public int AtomicNumber { get; set; }
        public double AtomicMass { get; set; }
        public double Density { get; set; }
        public string Valencia { get; set; }
        public double MeltingPoint { get; set; }
        public double BoilingPoint { get; set; }
        public string StandarState { get; set; }
        public string SerialChemical { get; set; }
        public int Period { get; set; }
        public int Group { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

    }
}

Clase PeriodicTable

/* ****************************************************************
* © JOAQUIN MARTINEZ RUS 2016
* PROYECTO:        Tabla periódica
* Archivo:         PeriodicTable.cs
* Descripción:     Clase PeriodicTable.
 *
* Historial:
*                  1. 12 sep 2016. Creación
*
* Comentarios:     Tabla periódica
*
*
*******************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace DimitriMendeleyev
{
    public class PeriodicTable: INotifyPropertyChanged
    {
        public PeriodicTable()
        {
            Elements = new List<Element>();
            SerialChemical = new List<string>();
            SerialChemical.AddRange(new string[] { "Metales", "Metaloides" , "Otros no metales",
                "Halógenos", "Alcalinotérreos", "Alcalinos", "Metales de Transición",
                "Gases nobles", "Lantánidos", "Actínidos"});
            States = new List<string>();
            States.AddRange(new string[] { "Gas", "Líquido", "Sólido", "Artificial" });
        }

        public List<Element> Elements { get; set; }
        public List<string> SerialChemical { get; set; }
        public List<string> States { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Por último en la vista creo un control de usuario para un elemento de la tabla y que utilizaremos hasta en 108 ocasiones para crear nuestra tabla.
Cada elemento tiene una serie de propiedades como el número atómico, el símbolo, el nombre, la masa atómica, la serie química, el grupo, el periodo, el estado y un sinfín de propiedades. A este control definido, le asignamos mediante binding las propiedades que queremos mostrar y además le asigno la serie química mediante un color y el estado del elemento a 0ºC, (gas, sólido. líquido o artificial) mediante otro color. Para mostrar estos colores uso sendos conversores que a continuación muestro.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace DimitriMendeleyev
{
    public class SerialChemicalToColorConverter : IValueConverter
    {

        #region IValueConverter

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush scb = new SolidColorBrush();

            switch (value.ToString())
            {
                case "Metales":
                    scb.Color = Color.FromRgb(144,238,144);
                    break;
                case "Metaloides":
                    scb.Color = Color.FromRgb(126, 179, 126);
                    break;
                case "Otros no metales":
                    scb.Color = Color.FromRgb(47, 155, 47);
                    break;
                case "Halógenos":
                    scb.Color = Color.FromRgb(134, 221, 221);
                    break;
                case "Alcalinotérreos":
                    scb.Color = Brushes.Khaki.Color;
                    break;
                case "Alcalinos":
                    scb.Color = Brushes.Gold.Color;
                    break;
                case "Metales de Transición":
                    scb.Color = Brushes.BurlyWood.Color;
                    break;
                case "Gases nobles":
                    scb.Color = Brushes.SteelBlue.Color;
                    break;
                case "Lantánidos":
                    scb.Color = Brushes.SandyBrown.Color;
                    break;
                case "Actínidos":
                    scb.Color = Brushes.RosyBrown.Color;
                    break;
            }
            return scb;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return Color.FromRgb(255, 0, 0);
        }

        #endregion
    }

    public class StandarStateToColorConverter : IValueConverter
    {

        #region IValueConverter

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush scb = new SolidColorBrush();

            switch (value.ToString())
            {
                case "Gas":
                    scb.Color = Brushes.LightBlue.Color;
                    break;
                case "Líquido":
                    scb.Color = Brushes.Blue.Color;
                    break;
                case "Sólido":
                    scb.Color = Brushes.Black.Color;
                    break;
                case "Artificial":
                    scb.Color = Brushes.DarkRed.Color;
                    break;
            }
            return scb;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return Color.FromRgb(255, 0, 0);
        }

        #endregion
    }
}

En cuanto al elemento, contiene un Grid con un control Button y un StackPanel con tres controles Textblock que mostrarán las propiedades mediante binding. Es de reseñar que el modo que usan los enlaces a datos es OneTime, ya que los datos solo se mostrarán una sola vez y no habrá modificaciones; con esto conseguimos menos sobrecarga sobre la aplicación y economía de medios y recursos.

<UserControl x:Class="DimitriMendeleyev.ElementControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DimitriMendeleyev"
             mc:Ignorable="d"
             xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
             d:DesignHeight="60" d:DesignWidth="60" x:Name="_element">
    <UserControl.Resources>
        <local:SerialChemicalToColorConverter x:Key="sctcc"/>
        <local:StandarStateToColorConverter x:Key="sstcc"/>
    </UserControl.Resources>
    <Grid>
        <Button Width="auto" Height="auto"
                Background="{Binding Path=SerialChemical, Converter={StaticResource sctcc}, Mode=OneTime}"
                x:Name="buttonElement">
            <StackPanel>
                <TextBlock x:Name="AtomicNumberTextBlock" Text="{Binding AtomicNumber, Mode=OneTime}" FontSize="12" TextAlignment="Center"/>
                <TextBlock x:Name="SymbolTextBlock" Text="{Binding Symbol, Mode=OneTime}" FontSize="15" TextAlignment="Center" FontWeight="Bold" Foreground="{Binding StandarState, Converter={StaticResource sstcc}}"/>
                <TextBlock x:Name="NameTextBlock" Text="{Binding Name, Mode=OneTime}" FontSize="10" TextAlignment="Center" />
            </StackPanel>
        </Button>
    </Grid>
</UserControl>

He creado otro control de usuario que muestra los datos ampliados del elemento de la tabla seleccionado y funciona prácticamente igual pero con la diferencia que se le pasa cada vez que se pulsa sobre un elemento concreto, este elemento, traspasa sus datos mediante el DataContext propio al control de datos ampliados.
Elemento con selección

<UserControl x:Class="DimitriMendeleyev.BigElementControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DimitriMendeleyev"
             mc:Ignorable="d"
             d:DesignHeight="220" d:DesignWidth="250" x:Name="big">
    <UserControl.Resources>
        <local:SerialChemicalToColorConverter x:Key="sctcc"/>
        <local:StandarStateToColorConverter x:Key="sstcc"/>
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200*"/>
            <ColumnDefinition Width="50*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30*"/>
        </Grid.RowDefinitions>
        <Border BorderBrush="Navy" BorderThickness="4"
                Width="auto" Height="auto" Margin="1"
                Background="{Binding Path=SerialChemical, Converter={StaticResource sctcc}}"
                Grid.ColumnSpan="2" Grid.RowSpan="6"/>
        <TextBlock x:Name="AtomicNumberTextBlock" Text="{Binding AtomicNumber}" FontSize="20" TextAlignment="Center" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>
        <TextBlock x:Name="SymbolTextBlock" Text="{Binding Symbol}" FontSize="30" TextAlignment="Center" FontWeight="Bold" Grid.Row="1" Grid.Column="0" Foreground="{Binding StandarState, Converter={StaticResource sstcc}}" Grid.ColumnSpan="2"/>
        <TextBlock x:Name="NameTextBlock" Text="{Binding Name}" FontSize="20" TextAlignment="Center" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"/>
        <TextBlock Text="{Binding AtomicMass, StringFormat='Masa Atómica: {0}'}" FontSize="14" TextAlignment="Center" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"/>
        <TextBlock Text="{Binding Density, StringFormat='Densidad: {0}'}" FontSize="14" TextAlignment="Center" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"/>
        <TextBlock Text="{Binding Valencia}" FontSize="14" TextAlignment="Center" Grid.Row="0" Grid.Column="1" Grid.RowSpan="4" TextWrapping="Wrap" Margin="5"/>
    </Grid>
</UserControl>

Paso del datacontext

        private void ButtonElement_Click(object sender, RoutedEventArgs e)
        {
            var buttonElement = e.OriginalSource as Button;
            var el = buttonElement.Parent as Grid;
            bigElement.DataContext = el.DataContext;
        }

La tabla periódica es la que tiene su «currito», tenemos que crear un control ElementControl por cada uno de los elementos de la tabla colocándolos en su sitio correcto, dejándolo lo más bonito que nuestro gusto nos permita. El código que contiene esta vista, no es otro que la instanciación de la clase XMLManager, la clase PeriodicTable y asignación al DataContext de la lista de elementos que contiene esta última. Muestro a continuación el código XAML completo de la tabla periódica.

<Controls:MetroWindow x:Class="DimitriMendeleyev.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
        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:local="clr-namespace:DimitriMendeleyev"
        mc:Ignorable="d"
        Title="MainWindow" Height="800" Width="1140"
                      BorderBrush="{DynamicResource AccentColorBrush}"
                      BorderThickness="1" WindowState="Maximized" WindowStartupLocation="CenterScreen">
    <Controls:MetroWindow.Resources>
        <Style x:Key="baseStyle" TargetType="TextBlock">
            <Setter Property="TextAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="Margin" Value="2"/>
            <Setter Property="FontSize" Value="22"/>
            <Setter Property="Foreground" Value="DarkGray"/>
        </Style>
        <Style x:Key="serialChemicalStyle" TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="TextAlignment" Value="Left"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Margin" Value="10"/>
            <Setter Property="FontSize" Value="12"/>
            <Setter Property="TextWrapping" Value="Wrap"/>
            <Setter Property="Width" Value="auto"/>
        </Style>
        <local:SerialChemicalToColorConverter x:Key="sctcc"/>
        <local:StandarStateToColorConverter x:Key="sstcc"/>
    </Controls:MetroWindow.Resources>
    <Grid x:Name="grid" HorizontalAlignment="Center">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="40"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="20"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="80"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="60"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <!-- CONTROL GRANDE -->
        <local:BigElementControl x:Name="bigElement" Grid.Column="0" Grid.Row="9" Grid.ColumnSpan="3" Grid.RowSpan="3" Margin="10,0,0,0"/>
        <!-- Periodos -->
        <TextBlock Text="1" Grid.Column="0" Grid.Row="1" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="2" Grid.Column="0" Grid.Row="2" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="3" Grid.Column="0" Grid.Row="3" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="4" Grid.Column="0" Grid.Row="4" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="5" Grid.Column="0" Grid.Row="5" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="6" Grid.Column="0" Grid.Row="6" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="7" Grid.Column="0" Grid.Row="7" Style="{StaticResource baseStyle}"/>
        <!-- Grupos -->
        <TextBlock Text="1" Grid.Column="1" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="2" Grid.Column="2" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="3" Grid.Column="3" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="4" Grid.Column="4" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="5" Grid.Column="5" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="6" Grid.Column="6" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="7" Grid.Column="7" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="8" Grid.Column="8" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="9" Grid.Column="9" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="10" Grid.Column="10" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="11" Grid.Column="11" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="12" Grid.Column="12" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="13" Grid.Column="13" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="14" Grid.Column="14" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="15" Grid.Column="15" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="16" Grid.Column="16" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="17" Grid.Column="17" Grid.Row="0" Style="{StaticResource baseStyle}"/>
        <TextBlock Text="18" Grid.Column="18" Grid.Row="0" Style="{StaticResource baseStyle}"/>

        <!-- series quimicas-->
        <Grid Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="9" Grid.RowSpan="3" Height="183" VerticalAlignment="Bottom">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="35"/>
                <RowDefinition Height="35"/>
                <RowDefinition Height="35"/>
                <RowDefinition Height="35"/>
                <RowDefinition Height="35"/>
            </Grid.RowDefinitions>
            <!--Metaloides-->
            <Grid Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2,0,2,2">
                <Border Width="auto" Height="auto"  Background="{Binding Path=SerialChemical[1], Converter={StaticResource sctcc}}" CornerRadius="10,0,0,0"/>
                <TextBlock Text="{Binding Path=SerialChemical[1]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <!--No metales-->
            <Border Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="6" BorderBrush="MidnightBlue" BorderThickness="2,2,2,0" CornerRadius="0,10,0,0" Margin="2"/>
            <TextBlock Text="No metales" HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="6" TextAlignment="Center" FontSize="19" VerticalAlignment="Top"/>
            <Grid Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2" VerticalAlignment="Bottom">
                <Border Width="auto" Height="auto"  Background="{Binding Path=SerialChemical[2], Converter={StaticResource sctcc}}" CornerRadius="0,0,0,8"/>
                <TextBlock Text="{Binding Path=SerialChemical[2]}" Style="{StaticResource serialChemicalStyle}" FontSize="10"/>
            </Grid>
            <Grid Grid.Row="0" Grid.Column="5" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2" VerticalAlignment="Bottom">
                <Border Width="auto" Height="auto"  Background="{Binding Path=SerialChemical[3], Converter={StaticResource sctcc}}"/>
                <TextBlock Text="{Binding Path=SerialChemical[3]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <Grid Grid.Row="0" Grid.Column="7" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2" VerticalAlignment="Bottom">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[7], Converter={StaticResource sctcc}}" CornerRadius="0,0,8,0"/>
                <TextBlock Text="{Binding Path=SerialChemical[7]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <!--Metales-->
            <Border Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="10" BorderBrush="MidnightBlue" BorderThickness="2,2,2,0" CornerRadius="10,10,0,0" Margin="2"/>
            <TextBlock Text="Metales" HorizontalAlignment="Stretch" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="10" TextAlignment="Center" FontSize="19" VerticalAlignment="Top"/>

            <Grid Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[5], Converter={StaticResource sctcc}}" CornerRadius="0,0,0,10"/>
                <TextBlock Text="{Binding Path=SerialChemical[5]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <Grid Grid.Row="3" Grid.Column="2" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[4], Converter={StaticResource sctcc}}" />
                <TextBlock Text="{Binding Path=SerialChemical[4]}" Style="{StaticResource serialChemicalStyle}" FontSize="11"/>
            </Grid>
            <Grid Grid.Row="3" Grid.Column="4" Grid.ColumnSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[8], Converter={StaticResource sctcc}}" />
                <TextBlock Text="{Binding Path=SerialChemical[8]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <Grid Grid.Row="4" Grid.Column="4" Grid.ColumnSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[9], Converter={StaticResource sctcc}}" />
                <TextBlock Text="{Binding Path=SerialChemical[9]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <Grid Grid.Row="3" Grid.Column="6" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[6], Converter={StaticResource sctcc}}" />
                <TextBlock Text="{Binding Path=SerialChemical[6]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>
            <Grid Grid.Row="3" Grid.Column="8" Grid.ColumnSpan="2" Grid.RowSpan="2" Margin="2">
                <Border Width="auto" Height="auto" Background="{Binding Path=SerialChemical[0], Converter={StaticResource sctcc}}" CornerRadius="0,0,10,0"/>
                <TextBlock Text="{Binding Path=SerialChemical[0]}" Style="{StaticResource serialChemicalStyle}"/>
            </Grid>

        </Grid>

        <!-- Elementos -->
        <Grid Grid.Column="2" Grid.Row="1">
            <Border BorderBrush="{DynamicResource AccentColorBrush}" BorderThickness="1" Width="auto" Height="auto" Margin="1"/>
            <StackPanel>
                <TextBlock x:Name="AtomicNumberTextBlock" Text="NºAtóm." FontSize="12" TextAlignment="Center"/>
                <TextBlock x:Name="SymbolTextBlock" Text="Símbolo" FontSize="14" TextAlignment="Center" FontWeight="Bold"/>
                <TextBlock x:Name="NameTextBlock" Text="Nombre" FontSize="12" TextAlignment="Center"/>
            </StackPanel>
        </Grid>
        <StackPanel Grid.Column="3" Grid.Row="1" Grid.RowSpan="2">
            <TextBlock Text="{Binding States[0]}" Foreground="{Binding States[0], Converter={StaticResource sstcc}}" FontSize="14" FontWeight="Bold" TextAlignment="Center"/>
            <TextBlock Text="{Binding States[1]}" Foreground="{Binding States[1], Converter={StaticResource sstcc}}" FontSize="14" FontWeight="Bold" TextAlignment="Center"/>
            <TextBlock Text="{Binding States[2]}" Foreground="{Binding States[2], Converter={StaticResource sstcc}}" FontSize="14" FontWeight="Bold" TextAlignment="Center"/>
            <TextBlock Text="{Binding States[3]}" Foreground="{Binding States[3], Converter={StaticResource sstcc}}" FontSize="14" FontWeight="Bold" TextAlignment="Center"/>
        </StackPanel>
        <local:ElementControl DataContext="{Binding Elements[0]}" Grid.Column="1" Grid.Row="1"/>
        <local:ElementControl DataContext="{Binding Elements[1]}" Grid.Column="18" Grid.Row="1"/>
        <local:ElementControl DataContext="{Binding Elements[2]}" Grid.Column="1" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[3]}" Grid.Column="2" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[4]}" Grid.Column="13" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[5]}" Grid.Column="14" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[6]}" Grid.Column="15" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[7]}" Grid.Column="16" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[8]}" Grid.Column="17" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[9]}" Grid.Column="18" Grid.Row="2"/>
        <local:ElementControl DataContext="{Binding Elements[10]}" Grid.Column="1" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[11]}" Grid.Column="2" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[12]}" Grid.Column="13" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[13]}" Grid.Column="14" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[14]}" Grid.Column="15" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[15]}" Grid.Column="16" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[16]}" Grid.Column="17" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[17]}" Grid.Column="18" Grid.Row="3"/>
        <local:ElementControl DataContext="{Binding Elements[18]}" Grid.Column="1" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[19]}" Grid.Column="2" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[20]}" Grid.Column="3" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[21]}" Grid.Column="4" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[22]}" Grid.Column="5" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[23]}" Grid.Column="6" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[24]}" Grid.Column="7" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[25]}" Grid.Column="8" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[26]}" Grid.Column="9" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[27]}" Grid.Column="10" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[28]}" Grid.Column="11" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[29]}" Grid.Column="12" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[30]}" Grid.Column="13" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[31]}" Grid.Column="14" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[32]}" Grid.Column="15" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[33]}" Grid.Column="16" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[34]}" Grid.Column="17" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[35]}" Grid.Column="18" Grid.Row="4"/>
        <local:ElementControl DataContext="{Binding Elements[36]}" Grid.Column="1" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[37]}" Grid.Column="2" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[38]}" Grid.Column="3" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[39]}" Grid.Column="4" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[40]}" Grid.Column="5" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[41]}" Grid.Column="6" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[42]}" Grid.Column="7" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[43]}" Grid.Column="8" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[44]}" Grid.Column="9" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[45]}" Grid.Column="10" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[46]}" Grid.Column="11" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[47]}" Grid.Column="12" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[48]}" Grid.Column="13" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[49]}" Grid.Column="14" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[50]}" Grid.Column="15" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[51]}" Grid.Column="16" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[52]}" Grid.Column="17" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[53]}" Grid.Column="18" Grid.Row="5"/>
        <local:ElementControl DataContext="{Binding Elements[54]}" Grid.Column="1" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[55]}" Grid.Column="2" Grid.Row="6"/>

        <local:ElementControl DataContext="{Binding Elements[71]}" Grid.Column="4" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[72]}" Grid.Column="5" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[73]}" Grid.Column="6" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[74]}" Grid.Column="7" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[75]}" Grid.Column="8" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[76]}" Grid.Column="9" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[77]}" Grid.Column="10" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[78]}" Grid.Column="11" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[79]}" Grid.Column="12" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[80]}" Grid.Column="13" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[81]}" Grid.Column="14" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[82]}" Grid.Column="15" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[83]}" Grid.Column="16" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[84]}" Grid.Column="17" Grid.Row="6"/>
        <local:ElementControl DataContext="{Binding Elements[85]}" Grid.Column="18" Grid.Row="6"/>

        <local:ElementControl DataContext="{Binding Elements[86]}" Grid.Column="1" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[87]}" Grid.Column="2" Grid.Row="7"/>

        <local:ElementControl DataContext="{Binding Elements[103]}" Grid.Column="4" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[104]}" Grid.Column="5" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[105]}" Grid.Column="6" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[106]}" Grid.Column="7" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[107]}" Grid.Column="8" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[108]}" Grid.Column="9" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[109]}" Grid.Column="10" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[110]}" Grid.Column="11" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[111]}" Grid.Column="12" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[112]}" Grid.Column="13" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[113]}" Grid.Column="14" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[114]}" Grid.Column="15" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[115]}" Grid.Column="16" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[116]}" Grid.Column="17" Grid.Row="7"/>
        <local:ElementControl DataContext="{Binding Elements[117]}" Grid.Column="18" Grid.Row="7"/>

        <!--  Lineas de lantánidos y actínidos -->
        <Polygon Grid.Column="3" Grid.Row="6" Grid.RowSpan="6" Stroke="Blue"
              Grid.ColumnSpan="18" Points="2 2 2 318 58 318 58 198 962 198 962 318 975 318 975 180 58 180 58 2">
            <Polygon.Fill>
                <SolidColorBrush Color="Coral" Opacity="0.3"/>
            </Polygon.Fill>
        </Polygon>
        <!--<local:ElementControl Grid.Column="3" Grid.Row="6" Background="Beige" />
        <local:ElementControl Grid.Column="3" Grid.Row="7" Background="PaleGoldenrod" />-->
        <TextBlock Text="57-71" Grid.Column="3" Grid.Row="6" Style="{StaticResource baseStyle}" FontSize="16"/>
        <TextBlock Text="89-103" Grid.Column="3" Grid.Row="7" Style="{StaticResource baseStyle}" FontSize="16"/>

        <local:ElementControl DataContext="{Binding Elements[56]}" Grid.Column="4" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[57]}" Grid.Column="5" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[58]}" Grid.Column="6" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[59]}" Grid.Column="7" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[60]}" Grid.Column="8" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[61]}" Grid.Column="9" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[62]}" Grid.Column="10" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[63]}" Grid.Column="11" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[64]}" Grid.Column="12" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[65]}" Grid.Column="13" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[66]}" Grid.Column="14" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[67]}" Grid.Column="15" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[68]}" Grid.Column="16" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[69]}" Grid.Column="17" Grid.Row="10"/>
        <local:ElementControl DataContext="{Binding Elements[70]}" Grid.Column="18" Grid.Row="10"/>

        <local:ElementControl DataContext="{Binding Elements[88]}" Grid.Column="4" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[89]}" Grid.Column="5" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[90]}" Grid.Column="6" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[91]}" Grid.Column="7" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[92]}" Grid.Column="8" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[93]}" Grid.Column="9" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[94]}" Grid.Column="10" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[95]}" Grid.Column="11" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[96]}" Grid.Column="12" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[97]}" Grid.Column="13" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[98]}" Grid.Column="14" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[99]}" Grid.Column="15" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[100]}" Grid.Column="16" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[101]}" Grid.Column="17" Grid.Row="11"/>
        <local:ElementControl DataContext="{Binding Elements[102]}" Grid.Column="18" Grid.Row="11"/>

    </Grid>
</Controls:MetroWindow>

Con esto, podemos apreciar que podríamos implementar lo que quisiéramos sobre la tabla periódica sin necesidad de modificar ni una sola línea de código de las clases MVVM. Como ejemplo, podríamos incluir en la tabla un control Slider que cambie la temperatura, de modo que una vez superara o quedara por debajo de las temperaturas de fusión y ebullición, el estado de los elementos cambiaría y por tanto el color del símbolo también.

Y aquí el resultado

Tabla05.gif
Espero que os haya gustado y como no, si queréis que os pase el proyecto, no dudéis en escribir un comentario o ponerse en contacto conmigo.

Saludos amig@s

Nota: Esta vez el NameSpace se lo dedico, como no, al químico Dimitri Mendeleiev que descubrió el fantástico patrón con el que los elementos químicos quedan ordenados en su tabla periódica. La imagen de la cabecera, es un monumento en la ciudad de Bratislava en su honor.

Anuncio publicitario

Un comentario en “Tabla periódica

Deja una respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s