Showing posts with label Markup Extension. Show all posts
Showing posts with label Markup Extension. Show all posts

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 - 

Friday, July 22, 2011

Custom Markup Extension in WPF


WPF allows us to create our own custom Markup Extension. In XAML we can use markup extension inside curly braces { } for e.g. {Binding}, {StaticResource} etc. These markup extensions are provided by WPF. We create our own custom markup extension by deriving MarkupExtension class available in System.Windows.Markup namespace. In this post I will explain how to create a custom Markup Extension using simple example.

Simple steps to create custom markup extension
  1. Create a Class and derived it from MarkupExtension class.
  2. Override ProvideValue method of MarkupExtension class in your class.
  3. Return value from ProvideValue method after doing processing.

XAML
<TextBlock Margin="10" HorizontalAlignment="Center"
    Text="{local:FullNameExtension FirstName=Mitesh, LastName=Sureja}" />

Similarly this can be written as,

<TextBlock Margin="10" HorizontalAlignment="Center">
   <TextBlock.Text>
      <local:FullNameExtension FirstName="Mitesh" LastName="Sureja" />
   </TextBlock.Text>
</TextBlock>

Code
public class FullNameExtension : MarkupExtension
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public FullNameExtension() { }

    public FullNameExtension(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
       
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return LastName + ", " + FirstName;
    }
}











ProvideValue method is not using serviceProvider (IServiceProvider) object. We can utilize this object to get Target Element and Target Property. GetService method of IServiceProvider interface returns IProvideValueTarget and IProvideValueTarget interface provides TargetObject and TargetProperty. Using this target property we can covert and return our value to target type. Let’s have a look on below modified code which uses IServiceProvider object inside ProvideValue method.

public override object ProvideValue(IServiceProvider serviceProvider)
{
    IProvideValueTarget ipValueTarget =
        serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
    if (ipValueTarget == null) return null;

    //Get target element
    FrameworkElement targetElement = ipValueTarget.TargetObject as FrameworkElement;

    object length = LastName.Length + FirstName.Length;

    //Get target property
    DependencyProperty dp = ipValueTarget.TargetProperty as DependencyProperty;
    length = Convert.ChangeType(length, dp.PropertyType);

    return length;
}

In above example, I demonstrated simple way to use IServiceProvider and IProvideValueTarget in ProvideValue method but more complex scenarios could be possible.


Related Links –

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.