JeroenEijkhof
JeroenEijkhof

Reputation: 2222

How to bind a Dependency Property to anything in the XAML

(Using Silverlight 4.0 and VS 2010)
So I have created a property called Rank in my C# file. How do I now tie that to a control in the UserControl xaml file?

My code: (TopicListItem.xaml.cs)

    #region Rank (DependencyProperty)

    /// <summary> 
    /// Rank 
    /// </summary> 
    public int Rank
    {
        get { return (int)GetValue(RankProperty); }
        set { SetValue(RankProperty, value); }
    }
    public static readonly DependencyProperty RankProperty =
        DependencyProperty.Register("Rank", typeof(int), typeof(TopicListItem),
        new PropertyMetadata(0, new PropertyChangedCallback(OnRankChanged)));

    private static void OnRankChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((TopicListItem)d).OnRankChanged(e);
    }

    protected virtual void OnRankChanged(DependencyPropertyChangedEventArgs e)
    {

    }

    #endregion Rank (DependencyProperty)

I want to do this in my TopicListItem.xaml

...
<Textblock Text="{TemplateBinding Rank}"/>
...

but that doesn't really work.

Upvotes: 5

Views: 15842

Answers (4)

AnthonyWJones
AnthonyWJones

Reputation: 189555

If you need to bind a property in a Usercontrol's xaml to a property exposed by the same UserControl then use the following pattern:-

<TextBlock Text="{Binding Parent.Rank, ElementName=LayoutRoot}" />

Note that this makes the assumption that root content element inside the UserControl has been given the name "LayoutRoot".

Upvotes: 8

Will Dean
Will Dean

Reputation: 39530

You need to use Binding, not TemplateBinding,

Also you might want to look into how to get binding errors reported to you - the very helpful default behaviour in WPF is to leave you guessing about binding problems, but you can actually get lots of useful info if you turn it on.

Upvotes: 1

Akash Kava
Akash Kava

Reputation: 39956

<UserControl xmlns..... 
    x:Name="myUserControl">

....

<Textblock Text="{Binding Rank,ElementName=myUserControl}"/>

....

</UserControl>

You need to set ElementName to x:Name of UserControl, if x:Name is empty, define one.

Upvotes: 6

Femaref
Femaref

Reputation: 61497

probably <Textblock Text="{Binding Rank}"/>.

Upvotes: -1

Related Questions