我正在.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.Username
的Label
并不显示该值。
1条答案
按热度按时间7kjnsjlb1#
绑定缺少其源对象(即UserControl示例)的规范: