Passa ai contenuti principali

WP7 Tip : Cambiare il background di un controllo in base al tema

A seguito di un thread apparso sul forum Microsoft per lo sviluppo in Windows Phone vorrei riportare una implementazione di un converter che ci consente di cambiare il background di un controllo nello XAML in base al tema attivo.

Per cominciare “rubiamo” il tip del Genio Del Male riguardante il modo con cui determinare il tema attivo (link) e lo convertiamo in VB.NET. In particolare creiamo un metodo shared (ma andrebbe bene anche una proprietà shared) nella classe App della nostra applicazione:

  1. Public Shared Function GetCurrentTheme() As Theme
  2.     Dim bgc = App.Current.Resources("PhoneBackgroundColor").ToString()
  3.     If bgc = "#FF000000" Then
  4.         Return Theme.Dark
  5.     Else
  6.         Return Theme.Light
  7.     End If
  8. End Function

L’enumerazione Theme è definita nel seguente modo:

  1. Public Enum Theme
  2.     Dark
  3.     Light
  4. End Enum

A questo punto possiamo creare il nostro conveter:

  1. Imports System.Windows.Data
  2. Imports System.Windows.Media
  3.  
  4. Public Class ThemeColorConverter
  5.     Implements IValueConverter
  6.  
  7.     Private Function GetColorFromName(ByVal strColor As String) As Color?
  8.         Dim retColor As Color? = Nothing
  9.         Try
  10.             Dim propColor = GetType(Colors).GetProperty(strColor)
  11.             If propColor IsNot Nothing Then
  12.                 Dim value = propColor.GetValue(Nothing, Nothing)
  13.                 If value IsNot Nothing Then
  14.                     retColor = CType(value, Color)
  15.                 End If
  16.             End If
  17.         Catch ex As Exception
  18.             retColor = Nothing
  19.         End Try
  20.         Return retColor
  21.     End Function
  22.  
  23.     Private Function GetColorFromRGB(ByVal strColor As String) As Color?
  24.         Dim retColor As Color? = Nothing
  25.         strColor = strColor.Replace("#", "")
  26.         Dim a As Byte = 255
  27.         Dim r As Byte = 255
  28.         Dim g As Byte = 255
  29.         Dim b As Byte = 255
  30.         Dim start = 0
  31.         If strColor.Length = 6 Or strColor.Length = 8 Then
  32.             If strColor.Length = 8 Then
  33.                 a = Byte.Parse(strColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber)
  34.                 start = 2
  35.             End If
  36.             r = Byte.Parse(strColor.Substring(start, 2), System.Globalization.NumberStyles.HexNumber)
  37.             g = Byte.Parse(strColor.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber)
  38.             b = Byte.Parse(strColor.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber)
  39.             retColor = Color.FromArgb(a, r, g, b)
  40.         End If
  41.         Return retColor
  42.     End Function
  43.  
  44.     Private Function GetColor(ByVal strColor As String) As Color
  45.         Dim retColor As Color
  46.  
  47.         Dim tmpColor = GetColorFromName(strColor)
  48.         If Not tmpColor.HasValue Then
  49.             tmpColor = GetColorFromRGB(strColor)
  50.             If tmpColor.HasValue Then
  51.                 retColor = tmpColor.Value
  52.             End If
  53.         Else
  54.             retColor = tmpColor.Value
  55.         End If
  56.  
  57.         Return retColor
  58.     End Function
  59.  
  60.     Public Function Convert(ByVal value As Object,
  61.                             ByVal targetType As System.Type,
  62.                             ByVal parameter As Object,
  63.                             ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
  64.         If value IsNot Nothing Then
  65.             Dim brush As SolidColorBrush = Nothing
  66.             Dim values = value.ToString().Split("|"c)
  67.             If values.Count = 2 Then
  68.                 If App.GetCurrentTheme() = Theme.Light Then
  69.                     brush = New SolidColorBrush(GetColor(values(0)))
  70.                 Else
  71.                     brush = New SolidColorBrush(GetColor(values(1)))
  72.                 End If
  73.             End If
  74.             Return brush
  75.         Else
  76.             Return Nothing
  77.         End If
  78.     End Function
  79.  
  80.     Public Function ConvertBack(ByVal value As Object,
  81.                                 ByVal targetType As System.Type,
  82.                                 ByVal parameter As Object,
  83.                                 ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
  84.         Throw New NotImplementedException()
  85.     End Function
  86. End Class

La funzione GetColor ci consente di ricavare un oggetto Color a partire da una stringa nei seguenti formati #AARRGGBB, #RRGGBB o “nome colore” (con il nome che può essere uno dei colori possibili della classe Colors).

Il metodo Convert del nostro converter recupera l’argomento value che per convenzione dovrà essere una stringa con il seguente formato:

colore tema light|colore tema dark

Il metodo splitta la stringa Value per recuperare i due colori e, in base al risultato del metodo GetCurrentTheme (visto in precedenza), recupera il colore utilizzando la GetColor e crea un SolidBrush che restituisce al chiamante.

Il converter così scritto si può utilizzare direttamente in binding all’interno dello XAML.

Per fare questo è sufficiente referenziare il namespace opportuno:

  1. xmlns:my="clr-namespace:WP7ThemeBackground"

Inserire il converter nelle risorse dell’applicazione o della pagina:

  1. <phone:PhoneApplicationPage.Resources >
  2.     <my:ThemeColorConverter x:Key="TCC"></my:ThemeColorConverter>
  3. </phone:PhoneApplicationPage.Resources>

E, infine, mettere il convertitore in binding con il background del controllo desiderato:

  1. <Grid x:Name="LayoutRoot" Background="{Binding Converter={StaticResource TCC}, Source=Red|#AA00FF00}">

In questo esempio, il colore per il tema light è il rosso (Red) mentre quello per il tema dark è il colore #AA00FF00 (un verde con della trasparenza).

Lo XAML completo dell’esempio è il seguente:

  1. <phone:PhoneApplicationPage
  2.     x:Class="WP7ThemeBackground.MainPage"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  9.     xmlns:my="clr-namespace:WP7ThemeBackground"
  10.     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
  11.     FontFamily="{StaticResource PhoneFontFamilyNormal}"
  12.     FontSize="{StaticResource PhoneFontSizeNormal}"
  13.     Foreground="{StaticResource PhoneForegroundBrush}"
  14.     SupportedOrientations="Portrait" Orientation="Portrait"
  15.     shell:SystemTray.IsVisible="True" >
  16.     <phone:PhoneApplicationPage.Resources >
  17.         <my:ThemeColorConverter x:Key="TCC"></my:ThemeColorConverter>
  18.     </phone:PhoneApplicationPage.Resources>
  19.     <!--LayoutRoot is the root grid where all page content is placed-->
  20.     <Grid x:Name="LayoutRoot" Background="{Binding Converter={StaticResource TCC}, Source=Red|#AA00FF00}">
  21.         <Grid.RowDefinitions>
  22.             <RowDefinition Height="Auto"/>
  23.             <RowDefinition Height="*"/>
  24.         </Grid.RowDefinitions>
  25.  
  26.         <!--TitlePanel contains the name of the application and page title-->
  27.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
  28.             <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
  29.             <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
  30.         </StackPanel>
  31.  
  32.         <!--ContentPanel - place additional content here-->
  33.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
  34.     </Grid>
  35. </phone:PhoneApplicationPage>

 

Commenti

Post popolari in questo blog

VB.NET : Aggregare stringhe con LINQ

Tip facile facile, ma a qualcuno potrebbe servire. Supponiamo di avere una lista di stringhe (magari come risultato di una query LINQ) e di voler ottenere una stringa con la concatenazione delle stesse: Dim list = CreateList() Dim concatStr = (From s In list _ Select s).Aggregate( Function (currentString, nextString) currentString + nextString) MessageBox.Show(concatStr) Il metodo CreateList non ci interessa, in questo momento, ma crea una lista di oggetti String. Protected Function CreateList() As IEnumerable( Of String ) Dim list As String () = {" stringa1 ", " stringa2 ", " stringa3 ", " stringa4 ", " stringa5 "} Return list.AsEnumerable() End Function Questo metodo potrebbe restituire una qualsiasi lista di oggetti di cui, nella select successiva recuperiamo solo stringhe. La stessa tecnica è utilizzabile per concatenare stringhe inserendovi un carattere separatore Dim list = CreateList() Dim

VB.NET: SplashScreen con effetto fade-in

In questo post vorrei proporvi un modo per realizzare una splash screen per le nostre applicazioni Windows Form che appare progressivamente con un effetto fade. Supponiamo di avere il nostro progetto VB.NET in una soluzione Visual Studio 2008 in cui abbiamo il sorgente della nostra applicazione Windows Form. Inseriamo una splash screen utilizzando il menù Progetto->Aggiungi Nuovo Elemento e selezionando il tipo di elemento “Schermata Iniziale” A questo punto Visual Studio creerà, automaticamente, la schermata iniziale che possiamo personalizzare graficamente come vogliamo. Per poter fare in modo che questa finestra appaia nel momento in cui avviamo l’applicazione, è necessario aprire le proprietà del progetto e impostare la maschera di avvio: In questo modo, all’avvio dell’applicazione, la schermata appare immediatamente e scompare un attimo prima della visualizzazione della finestra dell’applicazione. Possiamo far apparire la schermata iniziale con un ef

VB.NET: Convertire un file DOC in RTF e PDF con office interop

In questo post vorrei proporvi del codice per poter convertire un file .doc in un file .rtf oppure .pdf utilizzando le API di interoperabilità di Office. Creeremo una classe, DocConverter, che esporrà le due funzionalità sopra citate. Cominciamo con il prevedere un attributo privato della classe che rappresenterà l’applicazione Word che utilizzeremo per la conversione. Creeremo l’istanza dell’attributo privato all’interno del costruttore della classe: Public Sub New () If Not CreateWordApp() Then Throw New ApplicationException(" Assembly di interoperabilità con Office non trovato! ") End If End Sub Private _wordApp As Word.ApplicationClass Protected Function CreateWordApp() As Boolean Dim retval = True Try _wordApp = New Word.ApplicationClass() _wordApp.Visible = False Catch ex As System.Exception _wordApp = Nothing retval = False End Try Return retval End Function La conve