带有ComboBox DataTemplate绑定的ListBox

时间:2017-07-19 08:36:07

标签: wpf data-binding

我目前Combobox的{​​{1}} Datatemplate。我已将Listbox绑定到Combobox。这很好。

我想要的是当string[]被更改时,Combobox的索引应该与数组中的字符串相关联。 即如果我在Listbox的第3行的Combobox中选择第4项,则我的数据应由< string(Listbox string),int(Combobox index)>但为了节省重复数据,我想将此数据用作我的Listbox绑定。

我在想我可以使用键值对,但我不确定如何将其绑定到Combobox中的Combobox(或者如果这是执行此操作的最佳方式)。

注意

显然,这意味着每个DataTemplate字符串一次只能与一个Combobox索引相关联。 因此,我希望每个Listbox字符串只能在Combobox中设置一次,即如果我在Listbox的索引4中选择Combobox索引3,那么{{已经有Listbox 3的索引5应该重置为空白。我可能会在Listbox已更改的事件中通过并重置另一个Combobox,如果它是相同的字符串。

示例

确定以下绑定有效;

Combobox

C#

Comboboxes

1 个答案:

答案 0 :(得分:0)

这是我最终使用的。请随时提出更好的答案。

<Window.Resources>
    <DataTemplate x:Key="lbxHeaderDataTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1.5*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label Content="{Binding Item1}"></Label>
            <ComboBox Name="cbxTest" Grid.Column="1" ItemsSource="{Binding 
                 Item2}" DisplayMemberPath="Key"
                SelectionChanged="cbxTest_SelectionChanged"></ComboBox>
        </Grid>
    </DataTemplate>

</Window.Resources>
<StackPanel Width="auto" Height="auto">
    <ListBox Name="lbxFields"
             ItemTemplate="{DynamicResource lbxHeaderDataTemplate}" 
             HorizontalContentAlignment="Stretch">
    </ListBox>
</StackPanel>

C#

private Dictionary<string, int> cbxOptions2 = new Dictionary<string, int>();
cbxOptions2.Add("", 0);
cbxOptions2.Add("Identifier", 0);
cbxOptions2.Add("Family Identifier", 0);
cbxOptions2.Add("File Path", 0);
for (int i = 0; i < 10; i++)
{
    lbxDatFields.Items.Add(new Tuple<string, Dictionary<string, int>>((i * 10).ToString(), cbxOptions2));
}

private void cbxTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox test = (ComboBox)sender;
    DependencyObject parent = VisualTreeHelper.GetParent(test);
    Label currentTxt = null;
    foreach (object o in ((Grid)parent).Children)
    {
        if (o is Label)
        {
            currentTxt = (Label)o;
        }
    }
}