我正在 .NET 6 中構建 WPF 應用程式。我有一個帶有屬性的 MainWindow。
public Profile SelectedProfile
{
get => _selectedProfile;
set
{
_selectedProfile = value;
OnPropertyChanged();
}
}
此屬性用于 MainWindow 的控制元件 - 由 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>
在主視窗中使用:
<TabItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="Lista aneksów">
<controls:AnnexListTab Profile="{Binding SelectedProfile}"></controls:AnnexListTab>
</TabItem>
問題是盡管PropertyChangedCallback使用正確的值呼叫,但Label系結到Profile.Username的值不顯示該值。怎么了?
uj5u.com熱心網友回復:
Binding 缺少其源物件的規范,即 UserControl 實體:
<Label Content="{Binding Profile.Username,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535019.html
