【问题标题】:select 1st option in combobox by default in windows store app在 Windows 商店应用程序中默认选择组合框中的第一个选项
【发布时间】:2014-10-29 15:50:01
【问题描述】:

我在 Windows 商店应用程序中使用组合框,并通过数据绑定填充它。但是在运行时,它会选择一个空选项。我想从组合框中的项目中选择第一个选项。我尝试在 xaml 中设置SelectedIndex="0",但它给出了问题,在组件初始化组合时 bcz 有 0 个元素。我不想使用代码隐藏。 (combo1.SelectedIndex = 0)。任何建议如何通过 xaml 做到这一点?

编辑:

<StackPanel Orientation="Horizontal">
                <TextBlock Text="Repository" Margin="10" VerticalAlignment="Center"/>
                <ComboBox Width="{StaticResource ComboWidth}" x:Name="repocombo" SelectedIndex="0" ItemsSource="{Binding Path=Repositories}" SelectionChanged="SearchCombo_SelectionChanged">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>
            </StackPanel>

它给出了“Windows.UI.Xaml.Markup.XamlParseException”,但如果我从中删除SelectedIndex="0",它对我来说很好。有指针吗?

【问题讨论】:

  • 显示你的完整代码..
  • 添加代码,它给出了problelm 'Windows.UI.Xaml.Markup.XamlParseException'
  • 当您有 SelectionChanged="SearchCombo_SelectionChanged" 的代码隐藏时,为什么不想要 combo1.SelectedIndex=0 的代码隐藏?

标签: c# xaml windows-store-apps


【解决方案1】:

您可以向您的 ViewModel(或可绑定数据)添加一个属性,以保留 SelectedItem(并绑定到 Combobox.SelectedItem),并且当您设置属性 Repositories 时,您还设置了 SelectedItem:

Repositories = GetData();
SelectedItem = Repositories.FirstOrDefault();

在您的 xaml 代码中:

<ComboBox ItemsSource="{Binding Path=SelectedItem}"[...]

【讨论】:

    【解决方案2】:
    <ComboBox SelectedItem="{Binding Path=SelectedItem}"[...]
    

    【讨论】:

    • 如果可能,请尝试在您的帖子中添加一些解释
    猜你喜欢
    • 2022-01-14
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多