首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >属性更改调用的回调,但未显示值

属性更改调用的回调,但未显示值
EN

Stack Overflow用户
提问于 2022-11-15 10:00:27
回答 1查看 19关注 0票数 0

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

代码语言:javascript
运行
复制
public Profile SelectedProfile
{
    get => _selectedProfile;
    set
    {
        _selectedProfile = value;
        OnPropertyChanged();
    }
}

此属性用于由ComboBox更新并显示在TextBoxes中的主窗口控件中。这是按要求工作的。我还制作了一个自定义控件,它也将使用此属性。

代码语言:javascript
运行
复制
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>

用于MainWindow:

代码语言:javascript
运行
复制
<TabItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="Lista aneksów">
    <controls:AnnexListTab Profile="{Binding SelectedProfile}"></controls:AnnexListTab>
</TabItem>

问题是,尽管使用适当的值调用PropertyChangedCallback,但绑定到Profile.UsernameLabel不显示该值。怎么了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-15 10:10:47

绑定缺少其源对象的规范,即UserControl实例:

代码语言:javascript
运行
复制
<Label Content="{Binding Profile.Username,
                 RelativeSource={RelativeSource AncestorType=UserControl}}"/>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74443706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档