Showing posts with label DynamicResource. Show all posts
Showing posts with label DynamicResource. Show all posts

Sunday, October 14, 2012

How to get list of System Colors in WPF


You might aware about available System Colors in Windows machine. You might have changed system colors using below window. If you change color and appearance of any item (e.g. color, font, size, font color etc.) it will change appearance and color of all the application available in windows. In short you can change system’s default appearance and color using below dialog.


In this post I will demonstrate how you can get available list of system colors dynamically using WPF application. Let’s have a look on below example.

XAML
<Window x:Class="WpfApplication1.SysColors"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="System Colors" Height="300" Width="300">
<Grid>
<DataGrid Name="grdSysColorList"
          AutoGenerateColumns="False"
          GridLinesVisibility="Vertical">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Color"
                                Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Margin="5">
                        <TextBlock.Background>
                            <SolidColorBrush Color="{Binding Color}" />
                        </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Name"
                            Binding="{Binding Name}"
                            Width="200"/>
    </DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

Code
public partial class SysColors : Window
{
public SysColors()
{
    InitializeComponent();
    LoadSystemColors();
}
public void LoadSystemColors()
{
    List<SysColorItem> sysColorList = new List<SysColorItem>();
    Type t = typeof(System.Windows.SystemColors);
    PropertyInfo[] propInfo = t.GetProperties();
    foreach (PropertyInfo p in propInfo)
    {
        if (p.PropertyType == typeof(Color))
        {
            SysColorItem list = new SysColorItem();
            list.Color = (Color)p.GetValue(new Color(),
                BindingFlags.GetProperty, null, null, null);
            list.Name = p.Name;

            sysColorList.Add(list);
        }
        else if (p.PropertyType == typeof(SolidColorBrush))
        {
            SysColorItem list = new SysColorItem();
            list.Color = ((SolidColorBrush)p.GetValue(new SolidColorBrush(),
                BindingFlags.GetProperty, null, null, null)).Color;
            list.Name = p.Name;

            sysColorList.Add(list);
        }
    }
    grdSysColorList.ItemsSource = sysColorList;
}
}

public class SysColorItem
{
public string Name { get; set; }
public Color Color { get; set; }
}
}

Output


In above example you can see DataGrid having two columns Color and Name. Color displays various system colors and name displays its name. I have retrieved this system colors using Reflection. First I have retrieved type of SystemColors and then retrieved all the properties having Color and SolidColorBrush type. In last i have bind that list of SystemColors to DataGrid.


How to apply system colors to WPF controls

In above example we saw how we can retrieve list of system colors dynamically. Now let’s see how you can apply system colors to WPF control.

<Button Background="{x:Static SystemColors.MenuHighlightBrush}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">



Above code demonstrates how you can apply MenuHighlightBrush to Button’s background. Similarly you can apply other system colors as well. SystemColors has all the colors defined as Static property so we have used {x:Static} markup to retrieve system color.

As per above example, if your application running and MenuHighlightBrush color is changed in background then your application will not display newly changed color. If you want to do so you can use DynamicResource markup. DynamicResource will update resources dynamically whenever it changed while your application is running. Let’s have a look on below code snippet which used DynamicResource.

<Button Background="{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
</Button>

In above code I have used DynamicResource markup to display resources dynamically. If MenuHighlightBrushKey changed in background then your application will display newly changed value.

Here one thing to noticed that I have used resource key in second example while in first example I have used brush. The reason behind that is DynamicResource markup uses resource key.

Hope you liked this post. You can checkout below link to know more about System Colors in WPF.
http://blogs.msdn.com/b/wpf/archive/2010/11/30/systemcolors-reference.aspx

See also –

Tuesday, October 11, 2011

Static vs Dynamic resources in WPF


A resource can be referenced as either static or dynamic resource. This can be done by using either Static resource markup extension or Dynamic resource markup extension. You can go through my post on Markupextension in WPF for more information about markup extension.

  1. The major difference between static and dynamic resources is “static resource will evaluate the resource only once while dynamic resource will be evaluated every time the resource needed”.
  2. Dynamic resource has more performance overhead than static resources because it look up for resources every time it requested or needed.
  3. Static resource is faster but it takes little more time to load page or window than dynamic resource because dynamic resources are loaded when you actually used those.
  4. If resource is defined on the element’s resources and the same element property is using the resource defined inside its resources then static resource not applied because it should appears afterwards. The same thing is valid for dynamic resource. Let’s have a look on below code snippet.
       Below code gives compile time error.
       <Grid Background="{StaticResource lightBlueColor}">
         <Grid.Resources>
            <SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
         </Grid.Resources>
       </Grid>
          The same is valid for dynamic resource
       <Grid Background="{DynamicResource lightBlueColor}">
         <Grid.Resources>
            <SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
         </Grid.Resources>
       </Grid>

Below example gives you clear picture about Static and Dynamic resource markup extension.

XAML
<Window.Resources>
    <SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>
<StackPanel Name="stkPanel">
    <Button Name="Button1" Content="Button1"
            Width="150" Height="40" Margin="5"
            Background="{StaticResource buttonBackground}"/>
    <Button Name="Button2" Content="Button2"
            Width="150" Height="40" Margin="5"
            Background="{DynamicResource buttonBackground}"/>
    <Button Name="Button3" Content="Button3"
            Width="150" Height="40" Margin="5"
            Background="{StaticResource buttonBackground}"/>
</StackPanel>

Code behind
void StaticAndDynamicResources_Loaded(object sender, RoutedEventArgs e)
{
    stkPanel.Resources["buttonBackground"] = Brushes.Yellow;
}

Output















As shown in above example, three buttons are using buttonBackground resource defined in windows.resources element. Button1 and Button3 are using static resource markup extension while button2 is using dynamic resource markup extension. After loading of my window, I have changed color of buttonBackground resource from Lightblue to Yellow in code behind. So when I run my application, Button2 will have yellow background and rest of the buttons will have LightBlue background. The reason behind for not changing background of Button1 and Button3 because both button uses static resource and static resource is loaded only once with application while button2 uses dynamic resource and it changes every time when it accessed. 


Hope you liked this article. Please feel free to write feedback/comments in comment section below.

See also - 

Wednesday, June 29, 2011

Markup Extensions in XAML


You can specify a value to an attribute using curly braces ‘{}’ is called as Markup Extensions in XAML. The most commonly used markup extensions in WPF are Binding, StaticResource, DynamicResources, RelativeSource, TemplateBinding etc. These all markup extensions are default provided by WPF. If you want you can create your own Markup Extension you can achieve it by deriving MarkupExtension class. Nested Markup Extensions also possible in XAML.

<Window.Resources>
<Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Red" />
</Style>
</Window.Resources>

<StackPanel>
      <Button Content="Click Me!" Style="{StaticResource MyStyle}" />
</StackPanel>

In above example Style attribute of Button uses StaticResource Markup Extension.