简体   繁体   中英

Combobox SelectedItem and Binding in UWP

Currently Developing an UWP Application having troubles with comboboxes.

I am binding an ObservableCollection to a combobox (it works)

var WarehouseList = new ObservableCollection<Warehouse>(taskmag.Result);
        WarehouseBox.ItemsSource = WarehouseList;

What I would like to do is to show a selecteditem when I load data into my form. I am not using MVVM and this is my Combox XAML

<ComboBox HorizontalAlignment="Stretch" Width="400" FontSize="32" Name="WarehouseBox" Margin="20,0,0,0">
 <ComboBox.ItemTemplate>
  <DataTemplate>
   <StackPanel Orientation="Horizontal" Width="Auto" Height="Auto">
    <TextBlock Text="{Binding Name}"/>
    <TextBlock Text="{Binding WarehouseID}" Name="MID" Visibility="Collapsed"/>
   </StackPanel>
  </DataTemplate>
 </ComboBox.ItemTemplate>
</ComboBox>

I have no idea where to start from as documentation always implies MVVM or some other thing I have not implemented. I am willing to change my items coll to List or IEnumerable if it can help solve the issue.

Any help is greatly appreciated.

Here's the full thing, let me know if it still doesn't work for you:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ComboBox x:Name="ComboBoxWarehouses">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Width="Auto" Height="Auto">
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>

    public MainPage()
    {
        this.InitializeComponent();
        var items = new ObservableCollection<Warehouse>();
        var item = new Warehouse() {Name = "selected"};
        items.Add(new Warehouse() { Name = "not selected"});
        items.Add(item);
        items.Add(new Warehouse() { Name = "Another Not Selected"});

        ComboBoxWarehouses.ItemsSource = items;
        ComboBoxWarehouses.SelectedItem = item;
    }

页

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM