从未设置 WinRT DependencyProperty

WinRT DependencyProperty is never set

我的 DependencyProperty 在自定义 UserControl 中有一些问题。

我需要以特定方式显示有关人员的信息。为了实现这一点,我有几个 UserControls 收到一个 List<PeopleList> 其中包含(显然)一个或多个人。

让我向您展示我的(简化的)代码,然后我将向您解释我的应用程序的实际行为。

这是我的用户控件:

public abstract class PeopleLine : UserControl
{
    public static readonly DependencyProperty PeopleListProperty =
        DependencyProperty.Register("PeopleList", typeof(List<PeopleModel>), typeof(PeopleLine), new PropertyMetadata(default(List<PeopleModel>)));

    public List<PeopleModel> PeopleList
    {
        get { return (List<PeopleModel>)GetValue(PeopleListProperty); }
        set { SetValue(PeopleListProperty, value); }
    }
}

然后我的 xaml :

<local:PeopleLine
    x:Class="MyApp.Controls.EventSheet.OnePeople"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyApp.Controls.EventSheet"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid
        Margin="0 5"
        VerticalAlignment="Top"
        Height="51">
        <TextBlock
            Grid.Column="1"
            HorizontalAlignment="Center"
            Foreground="Red"
            FontSize="25"
            Text="{Binding PeopleList[0].Name}"/>
    </Grid>
</local:PeopleLine>

这一切都从我的 Page 开始,它包含一个 ItemsControl 和一个正确的 ItemsSource (我已经检查过了)和一个 ItemTemplateSelector (也可以正常工作) .这是选择器使用的 DataTemplate 之一:

<DataTemplate x:Key="OnePeople">
    <peoplecontrols:OnePeople
        PeopleList="{Binding LinePeopleList}"/>
</DataTemplate>

我使用了几个在这里并不重要的模型,因为我简化了我的代码以仅包含最重要的信息。

所以,回到我的问题。当用字符串替换选择器的 DataTemplate 中的 peoplecontrols:OnePeople 并将 LinePeopleList[0].Name 设为 Text 时,我显示了正确的文本,证明此时我的数据是正确的。 问题是当放回我的 peoplecontrols:OnePeople 时,我的 DependencyProperty 从未设置。我在 PeopleList 的 setter 下了一个断点,但它永远不会触发。

我尝试了几次修改(尤其是 post 中给出的修改,因此已经尝试用 typeof(object) 替换 typeof(List<PeopleModel>))但没有成功。另外,我尝试将 DependencyProperty 替换为 string 并直接在 DataTemplate 中发送名称,但 setter 仍然没有被调用...

我现在没有更多的想法,也不明白我的代码有什么问题。任何帮助将不胜感激。 提前致谢。

托马斯

尝试在 UserControl 的构造函数 中添加以下行,在调用 InitializeComponent 之后:

(this.Content as FrameworkElement).DataContext = this;

我为此创建了一个示例应用程序。希望它能正确反映您的情况:

https://github.com/mikoskinen/uwpusercontrollistdp

如果您克隆该应用程序并 运行 它,您会发现绑定不起作用。但是,如果您取消注释 UserControl 中的 Datacontext = this 行,一切都应该正常。这是工作代码:

    public PeopleLine()
    {
        this.InitializeComponent();

        (this.Content as FrameworkElement).DataContext = this;
    }