【问题标题】:Can't Use combobox in C# code不能在 C# 代码中使用组合框
【发布时间】:2013-10-04 15:40:20
【问题描述】:

我想在 C# 中添加一个组合框,因为我不想一直添加相同的组合框。我的代码是我要添加的组合框。

    <ScrollViewer Margin="252,130,296,134" Grid.Row="1" VerticalAlignment="Top" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.HorizontalScrollMode="Disabled" ScrollViewer.ZoomMode="Disabled">
            <StackPanel >
                <ItemsControl x:Name="ic" Grid.Row="2">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid HorizontalAlignment="Left" VerticalAlignment="Center">
                                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                                    <Border BorderBrush="#C83245" Background="White"  BorderThickness="1">
                                        <ComboBox x:Name="cbSeletion" VerticalAlignment="Center" FontSize="14" Width="250" Height="40" Foreground="Black" Tapped="cbSeletion_Tapped">

                                        </ComboBox>
                                    </Border>
                                    <Border BorderBrush="#C83245" Background="White" BorderThickness="1">
                                        <TextBlock Text="{Binding Name}" FontSize="14" VerticalAlignment="Center" Width="350" Foreground="Black"/>
                                    </Border>
                                    <Border BorderBrush="#C83245" Background="White"  BorderThickness="1" >
                                        <TextBlock Text="{Binding Position}" FontSize="14" VerticalAlignment="Center" Width="250" Foreground="Black"/>
                                    </Border>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ScrollViewer>

我可以做什么来使用它?

【问题讨论】:

  • 为您的 ItemsControl 创建一个 Items ViewModel,并在其中包含数据项的集合。然后将您的 ComboBox.ItemsSource 绑定到每个 Item 的集合。

标签: c# xaml windows-8 combobox


【解决方案1】:

您可以将组合框 ItemsSource 绑定到视图模型中的 ObservableCollection:

<ComboBox ItemsSource="{Binding Items}"/>

属性:

ObservableCollection<string> _items = new ObservableCollection<string>();
public ObservableCollection<string> Items
{
     get
     {
          return _items;
     }
}

然后,您可以在该集合中添加项目或从该集合中添加项目,下拉列表中的项目将反映它。

【讨论】:

    【解决方案2】:

    如果你的项目真的很少,你可以直接在 XAML 中使用ComboBoxItem,但它仍然不是那么优雅。 MVVM 方法无疑是答案,尤其是对于 ComboBox 集合中的许多项目,因为它为您提供了更大的灵活性,并且逻辑没有那么硬编码。

    【讨论】:

    • 我添加了comboboxitem,也不能用了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多