簡體   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