繁体   English   中英

数据绑定-重用列表,但选择的项目不同

[英]Databinding — Reusing list, but different selecteditems

我有一个具有以下结构的数据网格:

Question 1  text question 1    <pull down>
Question 2  text question 2    <pull down>
Question 3  text question 3    <pull down>

下拉组合框均具有相同的选项:是,否,也许。 现在,我将这些选项放在一个可观察的集合中。

我的问题是:如何绑定组合框的选定项属性,以便它从与源observablecollection不同的对象中提取?

这是一些可以使我更清楚地知道要做什么的代码

   public class ViewModel
   {
       ObservableCollection<string> options;
       ObservableCollection<question> questions;
   }

   public class question
   {
       public string selectedOption;
   }

如果我正确理解了您的问题,我认为简短的答案是“您不能”。 WPF检查所选项目是否是itemssource的一部分,如果不是,则不会显示所选项目。 您试图为用户创建什么样的行为? 也许还有另一种方法可以实现您想要的。

编辑也许这个类似/重复的问题+答案也会对您有所帮助? 当item不属于ItemsSource集合时,如何设置ComboBox的SelectedItem?

如果我正确地解释了您的问题,那么您希望对问题的答案选项使用相同的来源列表,但要确保选择之间保持独立。 您正在寻找类似这样的东西吗?

XAML

<StackPanel>
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Question 1"/>
            <ComboBox x:Name="cbxOne" ItemsSource="{Binding Options}"
                        SelectedItem="{Binding Questions[0].selectedOption}"></ComboBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Question 2"/>
            <ComboBox ItemsSource="{Binding Options}"
                      SelectedItem="{Binding Questions[1].selectedOption}"></ComboBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Question 2"/>
            <ComboBox ItemsSource="{Binding Options}"
                      SelectedItem="{Binding Questions[2].selectedOption}"></ComboBox>
        </StackPanel>
    </StackPanel>
    <ListBox ItemsSource="{Binding Questions}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content ="{Binding selectedOption}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
</StackPanel>

代码隐藏

public partial class MainWindow : Window
{

    ViewModel vm;
    public MainWindow()
    {
        InitializeComponent();
        vm = new ViewModel();
        this.DataContext = vm;
    }


}
public class ViewModel
{
    public ObservableCollection<string> Options { get; set; }
    public ObservableCollection<question> Questions { get; set; }
    public ViewModel()
    {
        Options = new ObservableCollection<string> { "Yes", "No", "Maybe" };
        Questions = new ObservableCollection<question>();
        Questions.Add(new question());
        Questions.Add(new question());
        Questions.Add(new question());
    }

}

public class question
{
    public string selectedOption { get; set; }
}

捕获展示绑定作品

如果在测试构造函数中,我为类似这样的集合中的问题分配一个值

Questions[0].selectedOption = "Yes";
Questions[1].selectedOption = "bogus";

然后,第一个组合框将给出已经选择的“是”,因为在用作ItemSource的集合中存在“是”,但是第二个组合框将为空白,因为没有匹配值。 它仍然显示在底部,因为我没有在此处进行任何检查验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM