Home > Blockchain >  Dependency Property change callback called but value not displayed
Dependency Property change callback called but value not displayed

Time:11-15

I am building a WPF application in .NET 6. I have a MainWindow with a property.

public Profile SelectedProfile
{
    get => _selectedProfile;
    set
    {
        _selectedProfile = value;
        OnPropertyChanged();
    }
}

This property is used in controls of MainWindow- updated by ComboBox and displayed in TextBoxes. That works as desired. I have also made a Custom Control that will use this property too.

using System.Windows;
using System.Windows.Controls;
using AutoNfzSchedule.Models;

namespace AutoNfzSchedule.Desktop.Controls;

public partial class AnnexListTab : UserControl
{
    public static readonly DependencyProperty ProfileProperty =
        DependencyProperty.Register(
            nameof(Profile),
            typeof(Profile),
            typeof(AnnexListTab),
            new PropertyMetadata(new Profile { Username = "123" }, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
    }

    public Profile Profile
    {
        get => (Profile)GetValue(ProfileProperty);
        set => SetValue(ProfileProperty, value);
    }

    public AnnexListTab()
    {
        InitializeComponent();
    }
}

<UserControl x:Class="AutoNfzSchedule.Desktop.Controls.AnnexListTab"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Border Padding="10,10">
        <StackPanel>
            <Label>bla bla</Label>
            <Label Content="{Binding Profile.Username}"></Label>
        </StackPanel>
    </Border>
</UserControl>

used in MainWindow:

<TabItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="Lista aneksów">
    <controls:AnnexListTab Profile="{Binding SelectedProfile}"></controls:AnnexListTab>
</TabItem>

The problem is that despite PropertyChangedCallback is called with proper values, the Label bound to Profile.Username does not display the value. What's wrong?

CodePudding user response:

The Binding is missing a specification of its source object, i.e. the UserControl instance:

<Label Content="{Binding Profile.Username,
                 RelativeSource={RelativeSource AncestorType=UserControl}}"/>
  • Related