Hi, find the person in list1 und set selected value. Try following demo:
XAML:
<Window x:Class="WpfApp1.Window27"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp27"
mc:Ignorable="d"
Title="Window27" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Window.Resources>
<local:ConcatNameAndOption x:Key="concatNameAndLoc"/>
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding View}"
SelectedValue="{Binding SelectedPerson}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource concatNameAndLoc}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
And classes:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace WpfApp27
{
public class ViewModel
{
public ViewModel()
{
cvs.Source = list1;
// set selected value
SelectedPerson = list1.Find((p) =>
{
return p.Location == "Paris" && p.Name == "Michael";
});
}
public List<Person> list1 = new List<Person>()
{
new Person() { Location = "Chicago", Name = "Michael" },
new Person() { Location = "", Name = "Mario" },
new Person() { Location = "Paris", Name = "Michael" },
new Person() { Location = "Denver", Name = "Michael" }
};
CollectionViewSource cvs = new CollectionViewSource();
public ICollectionView View { get => cvs.View; }
public Person SelectedPerson { get; set; }
}
public class Person
{
public string Location { get; set; }
public string Name { get; set; }
}
public class ConcatNameAndOption : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Person valConv = value as Person;
string loc = valConv.Location;
if (loc != "") loc = " (" + loc + ")";
return valConv.Name + loc;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => value;
}
}