我隱藏定義與性質和構造函數這麼一個簡單的類:XAML綁定到代碼隱藏類屬性集合爲空(WPF)
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命名空間。
但是,我的清單完全是空的。運行時沒有綁定錯誤。
這是怎麼回事?這似乎是一個簡單的例子,不會運行。我覺得我錯過了一些「明顯的」。
感謝您的徹底回覆!我開始懷疑「本地:CurrentQuestion」,但不知道原因。我修改了您提供的用於在整個網格上設置上下文的答案,並且它通過使用「RelativeSource」集將綁定設置爲「CurrentQuestion」來工作。但很好的悲傷,它仍然感覺過度。 – Dan
順便說一句,實際上有一種方法可以使用'local:CurrentQuestion'來進行綁定嗎? – Dan
@Dan沒有'local:CurrentQuestion'這樣的東西。 'local:Question'是一種數據類型; 'CurrentQuestion'是你的'UserControl'的一個屬性。所以我不確定你的意思是這個問題。 –