Markup Extensions in WPF
In this article we are going to focus on Markup Extensions in WPF. They are used to extend capabilities of XAML(eXtensible Application Markup Language). the MarkupExtension class is present in the System.Xaml assembly.
In this article we are going to focus on Markup Extensions in WPF. They are used to extend capabilities of XAML(eXtensible Application Markup Language). the MarkupExtension class is present in the System.Xaml assembly.
the arguments can be passed either via constructor or properties.
Create a new WPF application and add a new class "RandomExtension" which must be inherited from the abstract class "MarkupExtension". Then implement this class by right clicking on the MarkupExtension class and selecting Implement Abstract class as shown below.
write the below code in the class which takes the values for from and to variables from the constructor. This class implements the ProvideValue method which is used to generate a random from between the from and to values provided by the user and then this new generated number is returned.
public class RandomExtension : MarkupExtension
{
readonly int _from, _to;
public RandomExtension(int from, int to)
{
_from = from;
_to = to;
}
public RandomExtension(int to)
: this(0, to)
{ }
public static readonly Random _rnd = new Random();
public override object ProvideValue(IServiceProvider serviceProvider)
{
//return a random number in the range provided by the constructors.
return (double)_rnd.Next(_from, _to);
}
}
In the Mainwindow.xaml file add the below code which sets the FontSize of the textblock to the random number generated by our RandomExtension class. In another textblock we are also displaying the same value using Binding markup extension class which is in built into WPF.
<StackPanel>
<TextBlock FontSize="{local:Random 10,100}" Text="Hello" x:Name="txt1"></TextBlock>
<TextBlock Text="{Binding ElementName=txt1, Path=FontSize}"></TextBlock>
</StackPanel>
Run the application and you will see a random number generated and assigned to the fontsize property of the textblock (txt1). The output is as shown below: