2010-11-15 67 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