Posted by: Zeeshan Amjad | January 17, 2010

## Priority Binding

If we take a look at the binding base class in WPF then we came to know that WPF provides three types of bindings. In other words there are three classes inherited by Binding base class as shown by this class diagram.

We have already seen example of binding and multi binding. Lets take a look at Priority binding. Priority binding is pretty much like a cascade binding where just like multi binding, we provide multiple sources. But unlike multi binding, in priority binding WPF is going to look them one by one and see if it can get value from any source. Of course the first one has the highest priority.

Unfortunately when i searched on the net to find examples of priority binding then i found all the samples including one in MSDN try to simulate this by using Sleep function of threading. They are trying to simulate the late behavior of getting value from the prosperities. What’s different in this example is, this example discuss one simple toy application rather than dummy sleep method to actually perform some operation.

Here we are going to calculate the total number of primes up to one very large number (in mathematics it is called prime counting function and represented by pi). First let’s take a look at our prime information class. This class also has two private method.

```  1: public class PrimesInfo

2: {

3:     private String _primes;

4:

5:     public PrimesInfo()

6:     {

8:         Primes = "0";

9:     }

10:

11:     public String DefaultValue

12:     { get; set; }

13:

14:     public String Primes

15:     {

16:         get

17:         {

18:             int no = CalculatePrimes(Int32.Parse(_primes));

19:             return no.ToString();

20:         }

21:         set

22:         {

23:             _primes = value;

24:         }

25:     }

26:

27:     // Calculate prime with slow method

28:     int CalculatePrimes(int number)

29:     {

30:         int total = 0;

31:

32:         for (int i = 2; i < number; i++)

33:         {

34:             if (IsPrime(i))

35:                 total++;

36:         }

37:

39:     }

40:

41:     bool IsPrime(int number)

42:     {

43:         for (int i = 2; i < number; i++)

44:         {

45:             if (number % 2 == 0)

46:                 return false;

47:         }

48:

49:         return true;

50:     }

51:
Here we explicitly select the slowest method to calculate the prime. The whole purpose is to spend as much time as possible to calculate the total number of prime to actually see the priority binding working. Here is a piece of XAML code to perform priority binding.
1: <TextBlock Margin="5" Name="txtPrimes" Grid.Column="1" Grid.Row="1"

2: 		   VerticalAlignment="Center">

3: 	<TextBlock.Text>

4: 		<PriorityBinding>

5: 			<Binding Path="Primes" IsAsync="True"/>

6: 			<Binding Path="DefaultValue"/>

7: 		</PriorityBinding>

8: 	</TextBlock.Text>

9: </TextBlock>

10:
Now our program will first look at Primes property and if couldn’t fine the value then it is going to look at other property DefaultValue. Here is a complete XAML code of this program.
1: <Window x:Class="WpfPriorityBinding.Window1"

2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

4:     xmlns:local="clr-namespace:WpfPriorityBinding"

5:     Title="Priority Binding" Height="200" Width="300">

6:     <Grid Background="AliceBlue">

7:         <Grid.ColumnDefinitions>

8:             <ColumnDefinition/>

9:             <ColumnDefinition/>

10:         </Grid.ColumnDefinitions>

11:         <Grid.RowDefinitions>

12:             <RowDefinition/>

13:             <RowDefinition/>

14:         </Grid.RowDefinitions>

15:         <TextBlock Margin="5" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center"

16:                    Text="One very large no is"/>

17:         <TextBlock Margin="5" Name="txtNumber" Grid.Column="1" Grid.Row="0"

18:                  VerticalAlignment="Center" Text="54321"/>

19:         <TextBlock Margin="5" Grid.Column="0" Grid.Row="1" VerticalAlignment="Center"

20:                    Text="Total Number of Primes"/>

21:         <TextBlock Margin="5" Name="txtPrimes" Grid.Column="1" Grid.Row="1"

22:                    VerticalAlignment="Center">

23:             <TextBlock.Text>

24:                 <PriorityBinding>

25:                     <Binding Path="Primes" IsAsync="True"/>

26:                     <Binding Path="DefaultValue"/>

27:                 </PriorityBinding>

28:             </TextBlock.Text>

29:         </TextBlock>

30:     </Grid>

31: </Window>

32:
In C# program we create an object of our prime info class and set it as a data context in our main window. Here is our complete C# code of our program.
1: using System;

2: using System.Collections.Generic;

3: using System.Linq;

4: using System.Text;

5: using System.Windows;

6: using System.Windows.Controls;

7: using System.Windows.Data;

8: using System.Windows.Documents;

9: using System.Windows.Input;

10: using System.Windows.Media;

11: using System.Windows.Media.Imaging;

13: using System.Windows.Shapes;

14:

15: namespace WpfPriorityBinding

16: {

17:     /// <summary>

18:     /// Interaction logic for Window1.xaml

19:     /// </summary>

20:     public partial class Window1 : Window

21:     {

22:         public PrimesInfo primeInfo = new PrimesInfo();

23:         public Window1()

24:         {

25:             InitializeComponent();

26:             DataContext = primeInfo;

27:

28:             int number = Convert.ToInt32(txtNumber.Text);

29:             primeInfo.Primes = txtNumber.Text;

30:         }

31:     }

32:

33:     public class PrimesInfo

34:     {

35:         private String _primes;

36:

37:         public PrimesInfo()

38:         {

40:             Primes = "0";

41:         }

42:

43:         public String DefaultValue

44:         { get; set; }

45:

46:         public String Primes

47:         {

48:             get

49:             {

50:                 int no = CalculatePrimes(Int32.Parse(_primes));

51:                 return no.ToString();

52:             }

53:             set

54:             {

55:                 _primes = value;

56:             }

57:         }

58:

59:         // Calculate prime with slow method

60:         int CalculatePrimes(int number)

61:         {

62:             int total = 0;

63:

64:             for (int i = 2; i < number; i++)

65:             {

66:                 if (IsPrime(i))

67:                     total++;

68:             }

69:

71:         }

72:

73:         bool IsPrime(int number)

74:         {

75:             for (int i = 2; i < number; i++)

76:             {

77:                 if (number % 2 == 0)

78:                     return false;

79:             }

80:

81:             return true;

82:         }

83:     }

84: }

85:
Now if we run our program it will first display this window.

Then after some time, which depends on the computer speed how quickly it can calculate the total number of primes, we will see the following output.

__ATA.cmd.push(function() {
__ATA.initVideoSlot('atatags-370373-5b4e3a5bb36b3', {
sectionId: '370373',
});
});

__ATA.cmd.push(function() {
__ATA.initSlot('atatags-26942-5b4e3a5bb36e9',  {
collapseEmpty: 'before',
sectionId: '26942',
width: 300,
height: 250
});
});

__ATA.cmd.push(function() {
__ATA.initSlot('atatags-114160-5b4e3a5bb36eb',  {
collapseEmpty: 'before',
sectionId: '114160',
width: 300,
height: 250
});
});

Related
```

## Responses

1. IsPrime is wrongly implemented……

• Thanks for pointing out this. Yes there is a bug in IsPrime method, although there is a small typo, but it totally miss the algorithm. It should be something like this.

if (number % i == 0)
return false;