简体   繁体   中英

Dynamically select a Combo box item

I have a Combo box that is bound to a list Cities .

    <ComboBox Name="cmbCities"
         ItemsSource="{Binding Name}"
         DisplayMemberPath="Name"/>

    public class Cities
    {
        public string Name { get; set; }
        public int Pin { get; set; }
    }

I want to programmatically select NewYork in the combo whenever I click on btnSelectFavorite .

I tried-

        cmbCities.SelectedItem as Cities= "NewYork";

I get an error-

The left-hand side of an assignment must be a variable, property or indexer

Any help is appreciated.

Here's some code and markup to consider:

    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <StackPanel Orientation="Horizontal">
        <ComboBox ItemsSource="{Binding Cities}"
                  DisplayMemberPath="Name"
                  SelectedItem="{Binding SelectedCity}"
                  Width="160"
                  />
        <TextBlock Text="{Binding SelectedCity.Name}"/>
    </StackPanel>
</Window>

and

    public class MainWindowViewModel : BindableBase
    {
    public ObservableCollection<City> Cities { get; set; } = new ObservableCollection<City>(
        new List<City>
            {
                new City{Name="Liverpool", Pin=1},
                new City{Name="Manchester", Pin=2},
                new City{Name="London", Pin=3}
            }
        );
    private City selectedCity;
    public City SelectedCity
    {
        get => selectedCity;
        set { selectedCity = value; RaisePropertyChanged(nameof(SelectedCity)); }
    }
    }
public class City : BindableBase
{
    public string Name { get; set; }
    public int Pin { get; set; }
}

The window's datacontext is an instance of mainwindowviewmodel.

That presents a collection of city and it has a selectedcity property.

The comnbobox will set that selectedcity when the user selects one.

The city's name can then be used.

I'm binding it to the text of a textblock just to demonstrate it's selecting a city ok and the property is set.

EDIT:

Let's change this a bit so we can select a city.

The code I have uses prism so let's add a command - a delegatecommand.

This will get a reference to one of the cities and set selectedcity to that instance.

I'll also show you the Bindablebase SetProperty. This raises property changed (for the property) as well as setting the backing field.

And of course we need a button to click so we can invoke the command.

    Title="MainWindow" >
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <StackPanel Orientation="Horizontal">
        <ComboBox ItemsSource="{Binding Cities}"
                  DisplayMemberPath="Name"
                  SelectedItem="{Binding SelectedCity}"
                  Width="160"
                  />
        <TextBlock Text="{Binding SelectedCity.Name}"
                   MinWidth="100"/>
    <Button Content="New York Select"
                Command="{Binding SelectNYCommand}"/>
</StackPanel>
</Window>

and

    public class MainWindowViewModel : BindableBase
    {
    public ObservableCollection<City> Cities { get; set; } = new ObservableCollection<City>(
        new List<City>
            {
                new City{Name="Liverpool", Pin=1},
                new City{Name="Manchester", Pin=2},
                new City{Name="London", Pin=3},
                new City{Name="New York", Pin=4}
            }
        );
    private City selectedCity;
    public City SelectedCity
    {
        get => selectedCity;
        set { SetProperty(ref selectedCity, value); }
    }
    public DelegateCommand SelectNYCommand { get; private set; }

    public MainWindowViewModel()
    {
        SelectNYCommand = new DelegateCommand(() =>
        {
            var ny = Cities.Where(x => x.Name == "New York").FirstOrDefault();
            if(ny != null)
            {
                SelectedCity = ny;
            }
        });
    }

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