Domanda

Ho un semplice controllo utente

XAML:

<UserControl x:Class="GraemeGorman_Controls.Navigation.NavigationItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Border x:Name="borderLayoutRoot">
        <TextBlock x:Name="textBlockCaption" Text="{Binding Caption}" />
    </Border>
</UserControl>

Cs:

namespace GraemeGorman_Controls.Navigation
{
    public partial class NavigationItem : UserControl
    {
        public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register(
            "Caption",
            typeof (string),
            typeof (NavigationItem),
            new PropertyMetadata(new PropertyChangedCallback(OnCaptionChanged)));

        public string Caption
        {
            get {return (string)GetValue(CaptionProperty);}
            set {SetValue(CaptionProperty, value);}
        }

        public NavigationItem()
        {
            InitializeComponent();
        }

        private static void OnCaptionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //null
        }
    }
}

Qual è il mio problema, quando creo un'istanza del controllo che la didascalia non mostra mai - ora ho testato la proprietà nella funzione OnCaptionChanged utilizzando e.NewValue ed è il valore corretto. Cosa c'è di sbagliato nel mio legame?

Se scrivo nel codice dietro la proprietà caption per set

textBlockCaption.Text = value;

Sembra a posto ...

Qualsiasi aiuto apprezzato

Grazie Graeme

È stato utile?

Soluzione

Dal code-behind sembra che manchi una riga di codice.

Prova ad aggiungere DataContext = this; nel tuo costruttore. Questo ha funzionato per me in passato.

Altri suggerimenti

Come si crea l'istanza del controllo NavigationItem?

dovrai fare qualcosa del tipo:

<Page ...
  xmlns:gg="clr-namespace:GraemeGorman_Controls.Navigation">

<gg:NavigationItem Caption="FooBar" />

o persino

<gg:NavigationItem Caption="{Binding Path=TheCaption}" />

dove TheCaption è una proprietà del DataContext della tua pagina (ad es. ViewModel)

Spero che questo aiuti :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top