需要在调查表单中绑定来自不同来源和不同结构的ComboBox的selectedValue

时间:2012-04-12 17:19:58

标签: wpf wcf-binding

我在调查表中工作。调查是从具有以下结构的对象创建的:

调查 - has - >部分--has - >问题 - has - > QuestionOptions

每个QuestionOption都有:
QuestionID(与问题有关)
OptionText(将在ComboBox中显示的内容(DisplayMemeber绑定))
OptionValue(选项的分数,通常为1-5(SelectedValuePath绑定))

调查结果存储在以下结构中:

结果--has - >答案

每个答案都有:
QuestionID(将答案链接到数据库中的调查选项)
分数(这来自用户在ComboBox中的值选择)

保存工作正常,但如果我需要编辑调查,我需要恢复到目前为止所选择的结果。完整填充对象“结果”,因此我可以获得所有数据。

问题在GUI中:
我应该如何初始化或设置从DataTemplate创建的每个ComboBox与存储的调查的相应值?考虑到ComboBox是从对象“调查”生成的,答案在对象“结果”中

用于ComboBox的XAML代码是:

<DataTemplate x:Key="QuestonTemplate">
            <StackPanel Margin="10,2,10,2" Orientation="Vertical">
                <TextBlock HorizontalAlignment="Left" Text="{Binding Path=QuestionText}" TextWrapping="Wrap" Height="Auto" Margin="5" FontSize="14" />
                <ComboBox x:Name="Options" Grid.Row="1" HorizontalAlignment="Left" Width="400"  Margin="10,0,10,0" 
                    Style="{StaticResource FlatComboBoxPaleYellow}"                              
                    ItemsSource="{Binding Path=QuestionOptions}" 
                    SelectedValuePath="OptionValue" 
                    DisplayMemberPath="OptionText"                         
                    SelectionChanged="Answer_SelectionChanged" />
            </StackPanel>
        </DataTemplate>

我对XAML代码或C#(甚至更好!我是老上学)或任何建议持开放态度。

谢谢!

1 个答案:

答案 0 :(得分:0)

我建议您的Question对象包含一个附加属性:SelectedOption

这将是绑定到组合框的SelectedItem的数据:

<ComboBox x:Name="Options" Grid.Row="1" HorizontalAlignment="Left" Width="400"  Margin="10,0,10,0" 
                Style="{StaticResource FlatComboBoxPaleYellow}"                              
                ItemsSource="{Binding Path=QuestionOptions}" 
                SelectedValuePath="OptionValue" 
                DisplayMemberPath="OptionText"   
                SelectedItem="{Binding Path=SelectedOption}"                      
                SelectionChanged="Answer_SelectionChanged" />

然后在Survey对象中,对于Questions集合中的每个问题,找到Result对象中与该问题对应的任何Answers,在该问题上查找相应的QuestionOption并将其分配给该Question对象的SelectedOption属性

public class Question : INotifyPropertyChanged
{
    public QuestionOption SelectedOption
    {
        get
        {
            return _selectedOption;
        }
        set
        {
            if (value != _selectedOption)
            {
                _myList = value;
                OnPropertyChanged("SelectedOption");
            }
        }
    }
    private QuestionOption _selectedOption = new QuestionOption();

    // ... other properties ...
}
相关问题