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; }
    }
}
复制代码

 

posted @   simadi  阅读(417)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-02-24 纸黄金价格走势图
2016-02-24 Highcharts中文教程
点击右上角即可分享
微信分享提示