wpf 设置 listbox的选中项
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; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-02-24 纸黄金价格走势图
2016-02-24 Highcharts中文教程