用户控件库中的依赖项 属性 始终为空

Dependency Property in a user control library is always null

所以我得到了这个控件:

CharacterMapControl.xaml:

<UserControl x:Class="CharacterMap.CharacterMapControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:CharacterMap">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="350"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <TextBlock Text=""></TextBlock>
        </StackPanel>
    </Grid>


</UserControl>

然后 CharacterMapControl.xaml.cs:

using System.Windows;
using System.Windows.Controls;

namespace CharacterMap
{
    /// <summary>
    /// Interaction logic for CharacterMapControl.xaml
    /// </summary>
    ///     
    public partial class CharacterMapControl : UserControl 
    {
        public static readonly DependencyProperty FilepathProperty = DependencyProperty.Register("Filepath", typeof(string), typeof(CharacterMapControl));
        public string Filepath
        {
            get { return (string)GetValue(FilepathProperty); }
            set { SetValue(FilepathProperty, value); }
        }



        public CharacterMapControl()
        {
            InitializeComponent();
        }
    }
}

这是在 .NET Core 的 WPF 用户控件库中。

然后我添加了一个新的 WPF App .NET Core 项目并将 MainWindow.xaml 编辑为如下所示:

<Window x:Class="WPF_Control_Tester.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:charactermap="clr-namespace:CharacterMap;assembly=CharacterMap"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <charactermap:CharacterMapControl Filepath="D:\repos\WpfProjects\latinchars.xml"></charactermap:CharacterMapControl>
    </Grid>
</Window>

好吧 - 现在 CharacterMapControl.xaml.cs 中的文件路径始终为空。我不明白为什么。它已正确绑定并且应该映射到我在 MainWindow 中添加的文件路径或者?

构造 CharacterMapControl 时,依赖项 属性 值将为空,因为在定义依赖项 属性 时未指定默认值。

稍等构造完控件CharacterMapControl,就会引发loaded事件,此时依赖属性就会有初始化值。

修改构造函数如下将有助于理解更多。

        public CharacterMapControl()
        {
            InitializeComponent();

            var y = GetValue(FilepathProperty);
            Console.WriteLine(y);

            this.Loaded += (sender, args) =>
            {
                var x = GetValue(FilepathProperty);
                Console.WriteLine(x);
            };
        }

您尚未将 TextBlock 的文本 属性 绑定到任何内容。

当我尝试你的代码时,我添加了绑定:

        <TextBlock Text="{Binding Filepath, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

哪个有效