【问题标题】:How to access SelectedItem of ComboBox inside DataTemplate如何在 DataTemplate 中访问 ComboBox 的 SelectedItem
【发布时间】:2017-01-01 13:05:24
【问题描述】:

我有以下 XAML:

<ItemsControl x:Name="TextComboPairItemsControl" Grid.Row="1" Grid.ColumnSpan="2"
                  ItemsSource="{Binding Path=AllHeaders.Fields}">
         <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>

                        <TextBlock x:Name="TextBlock1" Text="{Binding}"
                                   Grid.Column="0" Margin ="2"/>
                        <ComboBox x:Name="ComboBox1" ItemsSource="{Binding ElementName=MainGrid, Path=DataContext.Tags}"
                                  SelectedItem="{Binding ElementName=MainGrid, Path=DataContext.TextComboPairList.Combo}"
                                  Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
    </ItemsControl>

现在,在我的代码中,我希望能够读取用户在每个 ComboBox 中选择的内容。为此我创建了一个类:

public class TextComboPair
{
    public string TextContent { get; set; }
    public string ComboContent { get; set; }
}

每一对 TextBlock 和 ComboBox 都有自己的上述类的对象。 我还创建了一个列表来存储所有这些数据对:

public List<TextComboPair> TextComboPairList 
{
    get; 
    set; 
}

它在我的 DataContext 中定义。

因此,例如,如果屏幕上显示了三个 TextBlock-ComboBox 对的列表,并且用户将在每个 ComboBox 中选择他需要的内容,我希望上面的列表中填充了该数据。

正如您在 XAML 中看到的,我将 Selected Item 绑定到此列表,但我一定做错了。

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf xaml combobox binding


    【解决方案1】:

    试试这个:

    <ComboBox x:Name="ComboBox1" ItemsSource="{Binding  Path=DataContext.Tags, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}}"
                                  SelectedItem="{Binding  RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}, Path=DataContext.TextComboPairList.Combo}"
                                  Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>
    

    【讨论】:

    • 不幸的是它没有用。我的清单仍然为空。实际上,使用此代码,我的 ComboBox 甚至不显示任何内容。可能是因为我没有任何 DataGrid。
    • 那么什么是mainGrid?
    • 嗯,它只是 Grid,而不是 DataGrid
    • 尝试用 ItemsControl 替换 DataGrid... 可能会帮助您或具有您想要的 DataContext 的父控件...
    • 您能否编辑您的答案,以便我明白您的意思?我对 WPF 和 XAML 还很陌生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 2021-02-26
    • 2013-11-11
    • 1970-01-01
    • 2011-11-24
    • 2011-01-10
    • 2011-07-05
    相关资源
    最近更新 更多