wpf 已调用依赖关系属性更改回调,但未显示值

k4ymrczo  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(106)

我正在.NET 6中构建一个WPF应用程序。我有一个具有属性的MainWindow。

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

这个属性用在MainWindow的控件中-由ComboBox更新并显示在TextBox中。它可以按需要工作。我还制作了一个自定义控件,它也将使用这个属性。

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>

在主窗口中使用:

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

问题是,尽管PropertyChangedCallback被调用了正确的值,但是绑定到Profile.UsernameLabel并不显示该值。

7kjnsjlb

7kjnsjlb1#

绑定缺少其源对象(即UserControl示例)的规范:

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

相关问题