【问题标题】:XAML binding to a codebehind class property collection is blank (WPF)XAML 绑定到代码隐藏类属性集合为空白 (WPF)
【发布时间】:2017-01-28 12:55:08
【问题描述】:

我的代码隐藏定义了一个带有属性和构造函数的简单类:

public class Question
{
    public string[] Answers
    {
        get; set;
    }
    public int CorrectAnswerIndex
    {
        get; set;
    }
    public Question(string[] answers, int correctIndex)
    {
        this.Answers = answers;
        this.CorrectAnswerIndex = correctIndex;
    }
}

然后存在一个该类型的公共对象,它在窗口的构造函数中被初始化,如下所示:

 CurrentQuestion = new Question(
     new string[] { "First", "Second", "Third", "Fourth" }, 2
 );

然后我有以下 XAML 以尝试打印出所述问题的所有可能答案。

<Grid Margin="150,150,150,150" DataContext="local:CurrentQuestion">
        <ListBox ItemsSource="{Binding Answers}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</Grid>

本地命名空间之前定义为 CLR 命名空间。

但是,我的列表完全是空的。运行时没有绑定错误。

这里发生了什么?这似乎是一个无法运行的简单示例。我觉得我错过了一些“明显的”。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    这将在ListBox.DataContext 中查找名为Answers 的属性,并尝试将其用于ItemsSource

    <ListBox ItemsSource="{Binding Answers}">
    

    ListBox.DataContext 将从父 Grid 继承。不幸的是,网格的DataContext 是一个字符串,而字符串没有一个名为Answers 的属性。所以Binding 不能做任何事情并给你null

    <Grid Margin="150,150,150,150" DataContext="local:CurrentQuestion">
        <ListBox ItemsSource="{Binding Answers}">
    

    XAML 隐式转换是按我的意思做的事情,因此会引起很多混乱。有时您可以将local:CurrentQuestion 放在属性值中并将其作为数据类型——但这不是其中之一。无论如何,数据类型并不是您要提供的。您想要该名称的属性。但是local: 是一个命名空间,一个像System.Windows.Controls 这样的字面CLR 命名空间,而不是对对象的引用。

    UserControl 中的 XAML 如何绑定到UserControl 的属性。如果是Window,请将UserControl 更改为Window

    <Grid Margin="150,150,150,150">
        <ListBox 
            ItemsSource="{Binding CurrentQuestion.Answers, RelativeSource={RelativeSource AncestorType=UserControl}}">
    

    我只是猜测CurrentQuestionUserControl 的属性。让我知道它是否在其他地方。

    您在更新CurrentQuestion 时也可能会遇到问题,除非它是一个依赖属性。如果它是像这样的普通旧 CLR 属性,则 UI 不会在其值更改时收到通知:

    public Question CurrentQuestion { get; set; }
    

    【讨论】:

    • 感谢您的详尽回复!我开始怀疑local:CurrentQuestion,但不知道确切原因。我修改了您提供的答案以在整个网格上设置上下文,它通过将绑定设置为 CurrentQuestionRelativeSource 集来工作。不过好心疼,还是觉得过分了。
    • 顺便问一下,实际上有没有办法使用local:CurrentQuestion 进行绑定?
    • @Dan 没有 local:CurrentQuestion 这样的东西。 local:Question 是一种数据类型; CurrentQuestion 是您的 UserControl 的属性。所以我不确定你的这个问题是什么意思。
    • 我想我很困惑您如何引用数据类型和引用属性。我会去那里的。
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2012-07-15
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2010-11-12
    相关资源
    最近更新 更多