C# 绑定到codebehind类属性集合的XAML为空(WPF)

C# 绑定到codebehind类属性集合的XAML为空(WPF),c#,wpf,xaml,C#,Wpf,Xaml,My codebehind定义了一个具有属性和构造函数的简单类,如下所示: public class Question { public string[] Answers { get; set; } public int CorrectAnswerIndex { get; set; } public Question(string[] answers, int correctIndex) {

My codebehind定义了一个具有属性和构造函数的简单类,如下所示:

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命名空间

然而,我的名单上却空空如也。运行时没有绑定错误


这是怎么回事?这似乎是一个无法运行的简单示例。我觉得我遗漏了一些“明显的东西”。

这将查看名为
Answers
的属性的
列表框.DataContext
,并尝试将其用于
项资源

<ListBox ItemsSource="{Binding Answers}">
XAML隐式转换是“做我想做的事”,因此会引起很多混乱。有时,您可以将
local:CurrentQuestion
放入属性值中,并将其作为数据类型,但这不是其中之一。而且数据类型并不是您想要提供的。你想要一个叫这个名字的房子。但是
local:
是一个名称空间,一个类似于
System.Windows.Controls的文本CLR名称空间,而不是对对象的引用

下面是
UserControl
中的XAML如何绑定到
UserControl
的属性。如果是
窗口
,请将
用户控件
更改为
窗口

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

这将查看名为
Answers
的属性的
ListBox.DataContext
,并尝试将其用于
itemsource

<ListBox ItemsSource="{Binding Answers}">
XAML隐式转换是“做我想做的事”,因此会引起很多混乱。有时,您可以将
local:CurrentQuestion
放入属性值中,并将其作为数据类型,但这不是其中之一。而且数据类型并不是您想要提供的。你想要一个叫这个名字的房子。但是
local:
是一个名称空间,一个类似于
System.Windows.Controls的文本CLR名称空间,而不是对对象的引用

下面是
UserControl
中的XAML如何绑定到
UserControl
的属性。如果是
窗口
,请将
用户控件
更改为
窗口

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

谢谢你的详细回复!我开始怀疑
local:CurrentQuestion
,但不知道确切原因。我修改了您提供的答案,以便在整个网格上设置上下文,它通过使用
RelativeSource
集将绑定设置为
CurrentQuestion
。但是,天哪,这感觉还是太过分了。顺便问一下,有没有办法用
local:CurrentQuestion
进行绑定?@Dan没有
local:CurrentQuestion
这样的东西<代码>本地:问题
是一种数据类型
CurrentQuestion
是您的
UserControl
的属性。所以我不确定这个问题是什么意思。我想我把如何引用数据类型和引用属性弄糊涂了。我会到的。谢谢你的详细回复!我开始怀疑
local:CurrentQuestion
,但不知道确切原因。我修改了您提供的答案,以便在整个网格上设置上下文,它通过使用
RelativeSource
集将绑定设置为
CurrentQuestion
。但是,天哪,这感觉还是太过分了。顺便问一下,有没有办法用
local:CurrentQuestion
进行绑定?@Dan没有
local:CurrentQuestion
这样的东西<代码>本地:问题
是一种数据类型
CurrentQuestion
是您的
UserControl
的属性。所以我不确定这个问题是什么意思。我想我把如何引用数据类型和引用属性弄糊涂了。我会到那里的。