Tuesday, May 17, 2011

Bindable Run - New Features in WPF 4.0



Bindable Run

Run element is used to display formatted text. Paragraph element uses Run element internally and Paragraph element mostly used in FlowDocuments.

In previous version of WPF, Run.Text element was not Bindable because it was implemented as normal CLR property but in WPF 4.0 Microsoft converted it to Dependency Property. So now Run.Text supports Binding and you can take full advantage of it. Please have a look on below example.

<Window x:Class="WPFTestApplication.BindableRun"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindableRun" Height="100" Width="300">
    <Window.Resources>
       <TextBlock Text="This is" x:Key="TextSample1" />
       <TextBlock Text=" Sample" x:Key="TextSample2" />
       <TextBlock Text=" Binding " x:Key="TextSample3" />
       <TextBlock Text=" on" x:Key="TextSample4" />
       <TextBlock Text=" Run." x:Key="TextSample5" />
    </Window.Resources>
    <StackPanel>
        <TextBlock Margin="10">
         <Run FontFamily="Arial" FontStyle="Italic"
             Text="{Binding Source={StaticResource TextSample1},
             Path=Text}" />
         <Run Background="Aqua"
             Text="{Binding Source={StaticResource TextSample2},
             Path=Text}" />
         <Run FontWeight="Bold" 
             Text="{Binding Source={StaticResource TextSample3},
             Path=Text}" />
         <Run Foreground="Brown"
             Text="{Binding Source={StaticResource TextSample4},
             Path=Text}" />
         <Run FontSize="25"
             Text="{Binding Source={StaticResource TextSample5},
             Path=Text}" />
        </TextBlock>
    </StackPanel>
</Window>

Output









No comments:

Post a Comment