所以我得到了此控件:
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中的Filepath始终为null。我不明白为什么。它绑定正确,应该映射到我在MainWindow中添加的Filepath还是?
构造CharacterMapControl时,依赖项属性值为null,因为在定义依赖项属性时未指定默认值。
构造控件CharacterMapControl之后不久,将引发已加载的事件,这时依赖项属性将具有初始化的值。
如下修改构造函数将有助于进一步了解。
public CharacterMapControl()
{
InitializeComponent();
var y = GetValue(FilepathProperty);
Console.WriteLine(y);
this.Loaded += (sender, args) =>
{
var x = GetValue(FilepathProperty);
Console.WriteLine(x);
};
}
您尚未将TextBlock的Text属性绑定到任何东西。
当我尝试您的代码时,我添加了绑定:
<TextBlock Text="{Binding Filepath, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
哪个作品