C# 绑定到codebehind类属性集合的XAML为空(WPF)
My codebehind定义了一个具有属性和构造函数的简单类,如下所示: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) {
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
的属性。所以我不确定这个问题是什么意思。我想我把如何引用数据类型和引用属性弄糊涂了。我会到那里的。