xaml
<Window x:Class="TestXiangmu.Views.Window1"
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:TestXiangmu.Views"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800">
<ListBox ItemsSource="{Binding Msgs}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValue="{Binding SelectMsg.Name}">
</ListBox>
</Window>
xaml.cs
using System.Windows;
using TestXiangmu.ViewModels;
namespace TestXiangmu.Views
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
private Window1ViewModel vm = new Window1ViewModel();
public Window1()
{
InitializeComponent();
this.DataContext = vm;
}
}
}
viewModel
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Prism.Mvvm;
namespace TestXiangmu.ViewModels
{
public class Window1ViewModel : BindableBase
{
public Window1ViewModel()
{
var msg = new List<Persion>
{
new Persion{Name = "feng",Year = 10},
new Persion{Name = "feng2",Year = 12},
new Persion{Name = "feng3",Year = 13},
};
Msgs=new ObservableCollection<Persion>(msg);
SelectMsg = new Persion { Name = "feng2", Year = 12 };
}
private ObservableCollection<Persion> _Msgs;
public ObservableCollection<Persion> Msgs
{
get => _Msgs;
set => SetProperty(ref _Msgs, value);
}
private Persion _SelectMsg;
public Persion SelectMsg
{
get => _SelectMsg;
set => SetProperty(ref _SelectMsg, value);
}
}
public class Persion
{
public string Name { get; set; }
public int Year { get; set; }
}
}