Silverlight中的列表框绑定

时间:2010-11-15 13:53:33

标签: data-binding silverlight-4.0 listbox

我在silverlight页面上有一个列表框,页面的datacontext设置为实例 - TestQuestions ,请参阅下面的代码。列表框使用DataTemplate,其ItemSource是' Answers ',这是页面的DataContext的属性,一切正常,直到我尝试绑定到' ShowAnswer ',属性在DataTemplate中的页面DataContext上。无论我尝试什么,它都不会选择房产的价值。

谢谢大家的帮助。

的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");
        }
    }

}

1 个答案:

答案 0 :(得分:0)

在我看来,你试图将UIElement.Visibility绑定到布尔值。将您的'ShowAnswer'属性从布尔值更改为Visibility属性,您应该设置。

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

修改

如果您尝试绑定到父控件的DataContext上的属性,则可以执行以下操作:

命名您的UserControl

示例:

<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">

在上面的示例中,UserControl的名称为“mainProtoPage”,现在在您的XAML中,您可以这样做:

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