2016-09-20 92 views
0

我隱藏定義與性質和構造函數這麼一個簡單的類: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命名空間。

但是,我的清單完全是空的。運行時沒有綁定錯誤。

這是怎麼回事?這似乎是一個簡單的例子,不會運行。我覺得我錯過了一些「明顯的」。

回答

2

這將看ListBox.DataContextAnswers屬性,並嘗試使用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隱式轉換是Do-What-I-Mean的事情,因此造成很多混淆。有時您可以將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; } 
+0

感謝您的徹底回覆!我開始懷疑「本地:CurrentQuestion」,但不知道原因。我修改了您提供的用於在整個網格上設置上下文的答案,並且它通過使用「RelativeSource」集將綁定設置爲「CurrentQuestion」來工作。但很好的悲傷,它仍然感覺過度。 – Dan

+0

順便說一句,實際上有一種方法可以使用'local:CurrentQuestion'來進行綁定嗎? – Dan

+0

@Dan沒有'local:CurrentQuestion'這樣的東西。 'local:Question'是一種數據類型; 'CurrentQuestion'是你的'UserControl'的一個屬性。所以我不確定你的意思是這個問題。 –