Here is the code of XAML:
<Window x:Class="WpfApp1.MainWindow"
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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ComboBox x:Name="CB" SelectedValue="{Binding Model,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Value" VerticalAlignment="Center">
</ComboBox>
</Grid>
</Window>
And here is the code of code-behind:
public partial class MainWindow : Window
{
public List<TestModel> Models { get; set; } = new List<TestModel>();
TestModel _Model = new TestModel() { Key = "Joe", Value = "456" };
public TestModel Model
{
get => _Model; set
{
if (_Model != value)
{
_Model = value;
}
}
}
public MainWindow()
{
InitializeComponent();
Models.Add(new TestModel() { Key = "John", Value = "123" });
Models.Add(new TestModel() { Key = "Joe", Value = "456" });
Models.Add(new TestModel() { Key = "Kay", Value = "547" });
Models.Add(new TestModel() { Key = "Rose", Value = "258" });
CB.ItemsSource = Models;
this.DataContext = this;
}
public class TestModel
{
public string Key { get; set; }
public string Value { get; set; }
}
}
I bind the SelectedValue
to the Model which is already existed in the List. but the selection is still blank.
What's wrong with my code? I need the combobox select the item correctly.