Dependency Properties In Windows 8.1

Dependency Properties

  1. Create a windows store blank app.

    app

  2. Add a user control in app,

    app

    app

  3. Create a textblock in usercontrol,
    1. <Grid>  
    2.     <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="50" Foreground="Aqua" />  
    3. </Grid>  
  4. Create a dependency property in code behind of user control either by coding or using shortcut propdp.
    1. public string TextBlockText  
    2. {  
    3.     get  
    4.     {  
    5.         return (string) GetValue(TextBlockTextProperty);  
    6.     }  
    7.     set  
    8.     {  
    9.         SetValue(TextBlockTextProperty, value);  
    10.     }  
    11. }  
    12.   
    13. // Using a DependencyProperty as the backing store for TextBlockText. This enables animation, styling, binding, etc...  
    14. public static readonly DependencyProperty TextBlockTextProperty =  
    15.     DependencyProperty.Register("TextBlockText"typeof(string), typeof(MyUserControl1), new PropertyMetadata(string.Empty));  
  5. Bind the textblock’s text property to the TextBlockText dependency property,
    1. <TextBlock Text="{Binding TextBlockText}"  
  6. Set datacontext for usercontrol so that the binding can work.
    1. public MyUserControl1()   
    2. {  
    3.     this.InitializeComponent();  
    4.     (this.Content as FrameworkElement).DataContext = this;  
    5. }  
  7. In main page create two instances of usercontrol to show the functioning of dependency properties.
    1. <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">  
    2.     <local:MyUserControl1 x:Name="control1" TextBlockText="Control 1 text" />  
    3.     <local:MyUserControl1 x:Name="control2" TextBlockText="Control 2 text" />  
    4. </StackPanel>  
  8. Run your application and check.

    application


Similar Articles