Binding a DP with a TextBlock inside the same UserControl RRS feed

  • Question

  • Hi,

    I have a UserControl: PlayerInformation.xaml 
    <Canvas x:Name="LayoutRoot" Background="Black">
         <TextBlock x:Name="TxtBlPlayerName" Text="{Binding PlayerName}" 
    Foreground="#FF8D7204" FontSize="10.667" Width="225" Height="15"
    ToolTipService.ToolTip="{Binding PlayerInformationNameDescription, Source={StaticResource Lang}}" /> </Canvas>
    This control has a DP:
      public string PlayerName
                get { return (string)GetValue(PlayerNameProperty); }
                set { SetValue(PlayerNameProperty, value); }
            // Using a DependencyProperty as the backing store for PlayerName.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty PlayerNameProperty =
                DependencyProperty.Register("PlayerName", typeof(string), 
    typeof(PlayerInformation), new PropertyMetadata(OnPlayerNameChange)); <br/>
    Can you please explain me how to bind this DP with the TextBlock in XAML ?

    i try: Text="{Binding PlayerName}"  but doesn't work, maybe i need an ElementName?

    In code, i try with the callback event ... but i want a cleanner way.

    • Edited by Fairydhwen Tuesday, December 29, 2009 1:48 PM better format
    Tuesday, December 29, 2009 1:47 PM


  • Your binding probably doesn't work because you haven't set the DataContext for your control.  In the code-behind for the UserControl's constructor, try adding this under the call to InitializeControl().

    this.DataContext = this;
    When the binding gets resolved, it will know to look at your control's DataContext, which is itself, and as long as your DP is in the control like you've said, it should magically work.
    • Proposed as answer by DaveyBoy1138 Tuesday, December 29, 2009 3:27 PM
    • Marked as answer by Fairydhwen Tuesday, December 29, 2009 3:51 PM
    Tuesday, December 29, 2009 3:26 PM