2010-11-15 69 views
1

我在silverlight頁面上有一個列表框,頁面的datacontext被設置爲一個實例 - TestQuestions,請參閱下面的代碼。該列表框使用DataTemplate,它的ItemSource是'答案',它是頁面的DataContext屬性,一切正常,直到我試圖綁定到'ShowAnswer',DataTemplate中頁面DataContext上的一個屬性。無論我嘗試什麼,它都不會選擇物業的價值。Silverlight中的列表框綁定

謝謝大家的幫助。

的XAML:

<ListBox ItemsSource="{Binding Path=Answers, Mode=TwoWay}"> 
<ListBox.ItemTemplate> 
    <DataTemplate> 
     <RadioButton IsChecked="{Binding Path=Correct, Mode=TwoWay}" > 
      <Grid> 
       <StackPanel Visibility="{Binding Path=ShowAnswer}"> 
        <Rectangle Fill="Blue" Visibility="{Binding Path=Correct}" /> 
       </StackPanel> 
       <TextBlock Text="{Binding Path=AnswerText, Mode=TwoWay}" TextWrapping="Wrap" /> 
      </Grid> 
     </RadioButton> 
    </DataTemplate> 
</ListBox.ItemTemplate> 

C#:

public class Answer 
{ 
    private bool correct = false; 
    public bool Correct 
    { 
     get { return correct; } 
     set 
     { 
      correct = value; 
      NotifyPropertyChanged("Correct"); 
     } 
    } 

    private string answerText = false; 
    public string AnswerText 
    { 
     get { return answerText; } 
     set 
     { 
      answerText = value; 
      NotifyPropertyChanged("AnswerText"); 

     } 
    } 

} 



public class TestQuestions 
{ 
    private ObservableCollection<Answer> answers = new ObservableCollection<Answer>(); 
    public ObservableCollection<Answer> Answers 
    { 
     get { return answers; } 
     set 
     { 
      if (answers != value) 
      { 
       answers = value; 
       NotifyPropertyChanged("Answers"); 
      } 
     } 
    } 

    private bool showAnswer = false; 
    public bool ShowAnswer 
    { 
     get { return showAnswer; } 
     set 
     { 
      showAnswer = value; 
      NotifyPropertyChanged("ShowAnswer"); 
     } 
    } 

}

回答

0

它看起來對我像你想的UIElement.Visibility綁定到一個布爾值。將您的'ShowAnswer'屬性從布爾值更改爲Visibility屬性,並且應該設置。

private Visibility showAnswer = Visibility.Collapsed; 
public Visibility ShowAnswer 
{ 
    get { return showAnswer; } 
    set 
    { 
     showAnswer = value; 
     NotifyPropertyChanged("ShowAnswer"); 
    } 
} 

編輯:

如果你想綁定到父控件的DataContext屬性,你可以這樣做:

名稱的用戶控件

例子:

<UserControl x:Class="MvvmLightProto.MainPage" 
     x:Name="mainProtoPage" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     mc:Ignorable="d" 
     Height="700" 
     Width="1200"> 

在上面的e xample,UserControl的名稱爲「mainProtoPage」,現在在您的XAML中,您可以這樣做:

<StackPanel Visibility="{Binding DataContext.ShowAnswer, ElementName=mainProtoPage}"> 
+0

感謝您的回覆。主要問題是我無法綁定到未在ItemSource對象中聲明的屬性。至於可見性綁定到一個布爾值,我實際上使用一個轉換器,它被排除在代碼之外。 – Charles 2010-11-16 19:52:22

+0

啊,我明白了。我編輯了我的答案,我想這就是你現在要找的。 – JSprang 2010-11-16 20:38:51

+0

再次感謝您的回覆JSprang。資源文件中聲明模板的情況是什麼?我嘗試使用資源文件正在使用的頁面的類名稱,但它不起作用。謝謝。 – Charles 2010-11-17 13:11:48