WPF ItemsControl implement Select in mvvm via behavior

news/2025/9/26 17:33:31/文章来源:https://www.cnblogs.com/Fred1987/p/19113913
<Window x:Class="WpfApp11.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:WpfApp11"xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"mc:Ignorable="d"WindowState="Maximized"Title="MainWindow" Height="450" Width="800"><Grid><ScrollViewer><ItemsControl x:Name="itemsControl" ItemsSource="{Binding ISBNSList}" ScrollViewer.CanContentScroll="True"ScrollViewer.VerticalScrollBarVisibility="Visible"ScrollViewer.IsDeferredScrollingEnabled="True"><!--<ItemsControl.ItemContainerStyle><Style TargetType="ContentPresenter"><EventSetter Event="MouseLeftButtonDown"Handler="ContentPresenter_MouseLeftButtonDown"/></Style></ItemsControl.ItemContainerStyle>--><ItemsControl.ItemTemplate><DataTemplate><Grid ShowGridLines="True"><behavior:Interaction.Triggers><behavior:EventTrigger EventName="MouseDown"><behavior:InvokeCommandActionCommand="{Binding DataContext.MouseLeftButtonDownCommand,RelativeSource={RelativeSource AncestorType=Window}}"CommandParameter="{Binding}"/></behavior:EventTrigger></behavior:Interaction.Triggers><Grid.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="50"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="FontSize" Value="100"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style><Style TargetType="ColumnDefinition"><Setter Property="Width" Value="Auto"/></Style></Grid.Resources><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBlock Text="{Binding Id}" Grid.Column="0"/><TextBlock Text="{Binding Name}" Grid.Column="1"/><TextBlock Text="{Binding ISBN}" Grid.Column="2"/><TextBlock Text="{Binding Title}" Grid.Column="3"/><TextBlock Text="{Binding Topic}" Grid.Column="4"/></Grid></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></ScrollViewer></Grid>
</Window>private void MouseLeftButtonDownCommandExecuted(object? obj)
{var bk = obj as Book;if(bk!=null){var bkJson=  JsonConvert.SerializeObject(bk, Formatting.Indented);MessageBox.Show(bkJson);}
}

 

 

 

 

 

 

 

 

image

 

 

image

 

Install-Package Microsoft.Xaml.Behaviors.Wpf;
Install-Package Newtonsoft.Json

 

 

 

 

 

//xaml
<Window x:Class="WpfApp11.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:WpfApp11"xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"mc:Ignorable="d"WindowState="Maximized"Title="MainWindow" Height="450" Width="800"><Grid><ScrollViewer><ItemsControl x:Name="itemsControl" ItemsSource="{Binding ISBNSList}" ScrollViewer.CanContentScroll="True"ScrollViewer.VerticalScrollBarVisibility="Visible"ScrollViewer.IsDeferredScrollingEnabled="True"><!--<ItemsControl.ItemContainerStyle><Style TargetType="ContentPresenter"><EventSetter Event="MouseLeftButtonDown"Handler="ContentPresenter_MouseLeftButtonDown"/></Style></ItemsControl.ItemContainerStyle>--><ItemsControl.ItemTemplate><DataTemplate><Grid ShowGridLines="True"><behavior:Interaction.Triggers><behavior:EventTrigger EventName="MouseDown"><behavior:InvokeCommandActionCommand="{Binding DataContext.MouseLeftButtonDownCommand,RelativeSource={RelativeSource AncestorType=Window}}"CommandParameter="{Binding}"/></behavior:EventTrigger></behavior:Interaction.Triggers><Grid.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="50"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="FontSize" Value="100"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style><Style TargetType="ColumnDefinition"><Setter Property="Width" Value="Auto"/></Style></Grid.Resources><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBlock Text="{Binding Id}" Grid.Column="0"/><TextBlock Text="{Binding Name}" Grid.Column="1"/><TextBlock Text="{Binding ISBN}" Grid.Column="2"/><TextBlock Text="{Binding Title}" Grid.Column="3"/><TextBlock Text="{Binding Topic}" Grid.Column="4"/></Grid></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></ScrollViewer></Grid>
</Window>//MainWindow.xaml.csusing System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;namespace WpfApp11
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();var vm = new MainVM();this.DataContext = vm;}private void ContentPresenter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){// Implement custom selection logic herevar item = ((ContentPresenter)sender).Content;// Your selection handling code
        }}public class MainVM : INotifyPropertyChanged{public MainVM(){InitData();MouseLeftButtonDownCommand = new DelCommand(MouseLeftButtonDownCommandExecuted);}private void MouseLeftButtonDownCommandExecuted(object? obj){var bk = obj as Book;if(bk!=null){var bkJson=  JsonConvert.SerializeObject(bk, Formatting.Indented);MessageBox.Show(bkJson);}}private void InitData(){ISBNSList = new ObservableCollection<Book>();for (int i = 1; i < 1001; i++){ISBNSList.Add(new Book(){Id = i,Name = $"Name_{i}",ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",Title = $"Title_{i}",Topic = $"Topic_{i}"});}}public event PropertyChangedEventHandler? PropertyChanged;private void OnPropertyChanged([CallerMemberName] string propName = ""){var handler = PropertyChanged;if (handler != null){handler?.Invoke(this, new PropertyChangedEventArgs(propName));}}private ObservableCollection<Book> iSBNSList;public ObservableCollection<Book> ISBNSList{get{return iSBNSList;}set{if (iSBNSList != value){iSBNSList = value;OnPropertyChanged();}}}public DelCommand MouseLeftButtonDownCommand { get; set; }}public class DelCommand : ICommand{private Action<object?> execute;private Predicate<object?> canExecute;public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue=null){execute = executeValue;canExecute = canExecuteValue;}public event EventHandler? CanExecuteChanged{add{CommandManager.RequerySuggested += value;}remove{CommandManager.RequerySuggested -= value;}}public bool CanExecute(object? parameter){return canExecute == null ? true : canExecute(parameter);}public void Execute(object? parameter){execute(parameter);}}public class Book{public int Id { get; set; }public string Name { get; set; }public string ISBN { get; set; }public string Title { get; set; }public string Topic { get; set; }}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/918605.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网站浮动广告怎么做优质的广州微网站建设

第一作者&#xff1a;Yang Zhao、Maedeh Amirmaleki通讯作者&#xff1a;TobinFilleter、蔡梅、孙学良通讯单位&#xff1a;加拿大多伦多大学、通用汽车研发中心、加拿大西安大略大学研究亮点&#xff1a;1.提出了锂金属负极“双层保护膜”的概念。2.通过ALD/MLD精确控制双层保…

做网站公司哪家强随便编一个公司网站

昨天晚上的直播甚是精彩 方同学不但分享了 获奖论文、解题技巧 还分享了 赛前准备、比赛经验和日程规划 po几张截图让大家感受下 此时此刻可能会有不少童鞋 正在为错过直播而懊悔 不用担心 超模君又准备了一份豪华大礼 本周 超模君特意邀请到 今年美赛A题特等奖获奖者 徐乾同学…

SI3933低频唤醒接收芯片完整指南:结构框图、PCB布局与选型要点芯片概述与主要特性

SI3933是一款三通道低功耗ASK接收机芯片,专为15kHz-150kHz低频载波频率检测而设计。这款芯片的主要功能是检测低频数字信号并产生唤醒信号,广泛应用于各种无线唤醒场景。 SI3933的核心特性包括其三通道ASK唤醒接收能…

在本地服务器创建RAID5磁盘阵列和RAID10磁盘阵列

在本地Vmware创建4个空白的磁盘 在虚拟机中添加4块新的硬盘 首先虚拟机处于关机状态下,点击编辑虚拟机设置: 选中“硬盘”:相同方法,添加4块硬盘,然后拉起服务器,就会看到4块新的盘,每块20G使用mdadm软件包,构…

RAGAS大模型评估框架

一、AGAs评估 RAGAs (Retrieval-Augmented Generation Assessment) 是一个框架,可以帮助快速评估RAG系统的性能,为了评估 RAG 系统,RAGAs 需要以下信息: question:用户输入的问题。answer:从 RAG 系统生成的答案(…

服务器密码错误被锁定如何解决?

当服务器因为密码错误多次输入而被锁定时,通常是由于安全策略(如 SSH 登录失败次数限制、防火墙规则或安全工具)触发的。这种情况可能导致无法远程登录服务器,但可以通过以下方法解决问题。以下是详细的排查和解决…

盐亭做网站网站站点建设

C语言允许宏带有参数。在宏定义中的参数称为“形式参数”&#xff0c;在宏调用中的参数称为“实际参数”&#xff0c;这点和函数有些类似。 对带参数的宏&#xff0c;在展开过程中不仅要进行字符串替换&#xff0c;还要用实参去替换形参。 带参宏定义的一般形式为&#xff1a…

音乐门户网站模板如何搭建网站

理解什么是关键字&#xff1f; Java赋予了某些单词特殊意义&#xff0c;就不能自己在代码中起同名一样的&#xff0c;否则提示错误 【在Java中关键字都是小写的&#xff0c;并不是所有的小写字母都是关键字&#xff0c;一般在IDEA中显示高亮橘黄色】 理解什么是保留字&#xf…

水翼式搅拌机推荐品牌/推荐厂家/优质供应商/哪家强?

水翼式搅拌机品牌推荐:南京兰江泵业——专业可靠的水处理设备专家 在污水处理和水体净化领域,水翼式搅拌机作为关键设备,其性能直接影响着整个系统的运行效率和效果。面对市场上众多品牌,如何选择一款质量可靠、性…

AutoMQ Ververica:打造云原生实时数据流最佳实践! - 教程

AutoMQ Ververica:打造云原生实时数据流最佳实践! - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Conso…

Java外功基础(1)——Spring Web MVC - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

100W QPS:亿级用户的社交关系如何设计?

当系统涌入亿级用户,100W QPS(每秒百万级请求) 是什么概念? 朋友圈里,大 V 发条动态,几百万粉丝同时收到推送; 直播间里,几十万人同时刷礼物、发弹幕; 电商大促,瞬间几千万下单请求直冲数据库。 没有合格的性…

php创建一个网站境外公司在国内建网站

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1卷积神经网络&#xff08;CNN&#xff09;在时间序列中的应用 4.2 长短时记忆网络&#xff08;LSTM&#xff09;处理序列依赖关系 4.3 注意力机制&#xff08;Attention&#xff09; 4…

建立网站要什么条件和多少钱wordpress主题零基础

java集合提取最小的日期我们都广泛使用了Collection类&#xff0c;例如List&#xff0c;Map及其派生版本。 每次使用它们时&#xff0c;我们都必须遍历它们以找到某个元素或更新这些元素&#xff0c;或者找到匹配某个条件的不同元素。 考虑如下所示的人员列表&#xff1a; Lis…

网上有做衣服的网站有哪些一键网站制作

Description 背景&#xff1a; 和久必分&#xff0c;分久必和。。。 题目描述&#xff1a; 中国历史上上分分和和次数非常多。。通读中国历史的WJMZBMR表示毫无压力。 同时经常搞OI的他把这个变成了一个数学模型。 假设中国的国土总和是不变的。 每个国家都可以用他的国土面积代…

做网站在哪里申请wordpress default

掌握 GoLang Fiber 中的路由和中间件艺术&#xff0c;以进行高效的 Web 开发 在网络开发领域中&#xff0c;创建一个有效地路由和管理各种任务的 Web 应用程序至关重要。路由决定了如何处理传入的请求&#xff0c;而中间件在执行任务&#xff0c;如身份验证、日志记录和请求解…

坤驰科技携数据采集解决方案,亮相中国光纤传感大会

2025年9月20日至22日,第十三届中国光纤传感大会在武汉光谷希尔顿酒店召开。大会吸引了来自国内外高校、科研院所及相关行业企业的千余名专家学者齐聚江城,共同探讨光纤传感技术的最新发展与未来趋势。 本届大会不仅汇…

新手入门需要掌握多少种大模型才行

新手入门,不在于“掌握多种”大模型,而在于“掌握一类”大模型的用法,并理解其背后的原理。 你不需要像背单词一样去学习几十种模型,关键在于建立正确的认知和方法论。下图清晰地展示了你的学习路径与目标:接下来…

docker容器怎么查看最后一些行日志

docker容器如果日志太多使用命令查看日志会一直刷很久才到尾部 docker logs -f 容器ID可以使用以下命令直接查看最后一些行日志 docker logs -f --tail 2000 b459e5d7a4eb