【问题标题】:Binding single property to parent items source将单个属性绑定到父项源
【发布时间】:2012-10-26 08:07:52
【问题描述】:

我想在 ListBox 中显示问题列表。每个 ListBoxItem 都包含问题和一个带有显示答案选项的 RadioButtons 的 ListBox。第一个 ListBox 的 ItemsSource 是一个带有 Question 类对象的可观察集合。第二个 ListBox 的 ItemsSource 是 QuestionClass 中的一个列表属性:QuestionObj.Answers。 我的问题是将 RadioButton 属性 GroupName 绑定到 Question 属性 QuestionObj.Index。我该如何解决这个问题?

这是问题类的代码:

public class Question
{
    private static int countQuestions;

    private int index;
    private string questionText;
    private List<String> answers = new List<String>();

    public Question()
    {
        countQuestions++;
    }
    public Question(string type, bool isRequired, string questionText, List<String> answers = null) :this()    
    {
        this.index = countQuestions;
        this.questionText = questionText;
        this.answers = answers;
    }

    public int Index
    {
        get { return index; }
    }
    public string QuestionText
    {
        get { return questionText; }
    }
    public List<String> Answers
    {
        get { return answers; }
    }
}

这里是 xaml:

<ListBox x:Name="Questions" ItemsSource="{Binding QuestionList}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Label Grid.Row="0" Content="{Binding QuestionText}"/>
                <ListBox x:Name="AnswerOptions" Grid.Row="1" ItemsSource="{Binding Answers}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <RadioButton Content="{Binding}" GroupName={Binding ??????}/>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    编辑: 将 SelectedIndex 更改为 SelectedItem.Index

    <RadioButton Content="{Binding}" 
                 GroupName={Binding ElementName=Questions, Path=SelectedItem.Index}/>
    

    看看这里。 www.nbdtech.com/Free/WpfBinding.pdf

    【讨论】:

    • 您的解决方案在这里不起作用,因为所有单选按钮都获得了 SelectedIndex 的值。我需要每个 qustion 的唯一索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多