我正在.NET 6中构建一个WPF应用程序,我有一个带有属性的MainWindow。
public Profile SelectedProfile
{
get => _selectedProfile;
set
{
_selectedProfile = value;
OnPropertyChanged();
}
}此属性用于由ComboBox更新并显示在TextBoxes中的主窗口控件中。这是按要求工作的。我还制作了一个自定义控件,它也将使用此属性。
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:
<TabItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="Lista aneksów">
<controls:AnnexListTab Profile="{Binding SelectedProfile}"></controls:AnnexListTab>
</TabItem>问题是,尽管使用适当的值调用PropertyChangedCallback,但绑定到Profile.Username的Label不显示该值。怎么了?
发布于 2022-11-15 10:10:47
绑定缺少其源对象的规范,即UserControl实例:
<Label Content="{Binding Profile.Username,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>https://stackoverflow.com/questions/74443706
复制相似问题