How to associate a dependency property with something in XAML

(Using Silverlight 4.0 and VS 2010)
So I created a property called Rankin my C # file. How now to bind this to a control in the xaml UserControl 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 ThemeListItem.xaml

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

but it does not work.

+3
source share
4 answers

If you need to bind a property in xaml Usercontrol with an object opened by the same UserControl, then use the following template: -

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

Note that this makes the assumption that the root content element inside the UserControl is named "LayoutRoot".

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

....

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

....

</UserControl>

ElementName x: Name UserControl, x: Name , .

+5

You need to use Binding, not TemplateBinding,

You can also see how to get binding error messages that you were informed about - a very useful default behavior in WPF is to leave you guessing about binding problems, but you can get a lot of useful information if you enable it.

+1
source

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

-1
source

Source: https://habr.com/ru/post/1753931/


All Articles