WPF ControlTemplate DI Via Microsoft.Extensions.DependencyInjection

news/2025/9/18 19:11:37/文章来源:https://www.cnblogs.com/Fred1987/p/19099517
Install-Package Microsoft.Extensions.DependencyInjection;
Install-Package CommunityToolkit.mvvm;

 

 

//app.xaml
<Application x:Class="WpfApp21.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp21"><Application.Resources></Application.Resources>
</Application>//app.xaml.cs
using Microsoft.Extensions.DependencyInjection;
using System.Windows;namespace WpfApp21
{/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : Application{ServiceProvider serviceProvider;protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);var services=new ServiceCollection();ConfigureServices(services);serviceProvider = services.BuildServiceProvider();var mainWin = serviceProvider.GetRequiredService<MainWindow>();mainWin?.Show();}private void ConfigureServices(ServiceCollection services){services.AddSingleton<INameService, NameService>();services.AddSingleton<IISBNService, ISBNService>();services.AddSingleton<IPriceService, PriceService>();services.AddSingleton<MainVM>();services.AddSingleton<MainWindow>();}protected override void OnExit(ExitEventArgs e){base.OnExit(e);serviceProvider?.Dispose();}}}//MainWindow.xaml
<Window x:Class="WpfApp21.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"WindowState="Maximized"xmlns:local="clr-namespace:WpfApp21"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><!--DataTemplate for ListBox items--><DataTemplate x:Key="ItemTemplate"><Border Background="#FFE3F2FD"CornerRadius="0"Padding="10"Margin="2"><StackPanel Width="{Binding DataContext.GridWidth,RelativeSource={RelativeSource AncestorType=Window}}"Height="{Binding DataContext.GridHeight,RelativeSource={RelativeSource AncestorType=Window}}"><TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="50"/><TextBlock Text="{Binding ISBN}" FontSize="40" TextWrapping="Wrap"/><TextBlock Text="{Binding Price,StringFormat='C'}"Foreground="Green" FontWeight="Bold"  FontSize="40" Margin="0,5,0,0"/></StackPanel></Border></DataTemplate><!--Custom ControlTemplate for ListBox--><ControlTemplate x:Key="lbxControlTemplate"TargetType="{x:Type ListBox}"><Border Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"CornerRadius="10"><ScrollViewer Padding="{TemplateBinding Padding}"Focusable="False"><ItemsPresenter/></ScrollViewer></Border></ControlTemplate><!--Style for ListBox--><Style x:Key="CustomListBoxStyle"TargetType="{x:Type ListBox}"><Setter Property="Template" Value="{StaticResource lbxControlTemplate}"/><Setter Property="Background" Value="#FFF5F5F5"/><Setter Property="BorderBrush" Value="#FFBDBDBD"/><Setter Property="BorderThickness" Value="1"/><Setter Property="Padding" Value="5"/><!--<Setter Property="ScrollViewer.HorizontalBarVisibity" Value="Auto"/><Setter Property="ScrollViewer.VerticalBarVisibility" Value="Auto"/>--><Setter Property="ScrollViewer.CanContentScroll" Value="True"/><Setter Property="VerticalContentAlignment" Value="Stretch"/><Setter Property="ItemTemplate" Value="{StaticResource ItemTemplate}"/><Style.Triggers><Trigger Property="ItemsControl.AlternationIndex" Value="0"><Setter Property="Background" Value="#FFF5F5F5"/></Trigger><Trigger Property="ItemsControl.AlternationIndex" Value="1"><Setter Property="Background" Value="#FFFFFFFF"/></Trigger></Style.Triggers></Style><!--Style for ListBoxItem--><Style TargetType="{x:Type ListBoxItem}"><Setter Property="SnapsToDevicePixels" Value="True"/><Setter Property="Padding" Value="4,2"/><Setter Property="HorizontalContentAlignment" Value="Stretch"/><Setter Property="VerticalContentAlignment" Value="Stretch"/><Setter Property="Background" Value="Transparent"/><Setter Property="BorderBrush" Value="Transparent"/><Setter Property="BorderThickness" Value="1"/><Setter Property="FocusVisualStyle" Value="{x:Null}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ListBoxItem}"><Border x:Name="Bd"Background="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"CornerRadius="6"SnapsToDevicePixels="True"><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"VerticalAlignment="{TemplateBinding VerticalContentAlignment}"SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Bd" Property="Background" Value="#FFBBDEFB"/><Setter TargetName="Bd" Property="BorderBrush" Value="#FF64B5F6"/></Trigger><Trigger Property="IsSelected"  Value="True"><Setter TargetName="Bd"  Property="Background" Value="#FF2196F3"/><Setter TargetName="Bd" Property="BorderBrush" Value="#FF1976D2"/></Trigger><MultiTrigger><MultiTrigger.Conditions><Condition Property="IsSelected" Value="True"/><Condition Property="IsMouseOver" Value="True"/></MultiTrigger.Conditions><Setter TargetName="Bd" Property="Background" Value="#FF1976D2"/><Setter TargetName="Bd" Property="BorderBrush" Value="#FF0D47A1"/></MultiTrigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><Grid><ListBox x:Name="customLbx"Style="{StaticResource CustomListBoxStyle}"ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"SelectionMode="Extended"Margin="20">           </ListBox></Grid>
</Window>//MainWindow.xaml.cs
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows;namespace WpfApp21
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public MainWindow(MainVM vm){InitializeComponent();this.DataContext=vm;this.SizeChanged+=MainWindow_SizeChanged;}private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e){if (this.DataContext is MainVM vm){var fe = this.Content as FrameworkElement;if (fe!=null){vm.GridWidth=fe.ActualWidth;vm.GridHeight=fe.ActualHeight/5;}}}}public partial class MainVM : ObservableObject{private INameService nameService;private IISBNService isbnService;private IPriceService priceService;public MainVM(INameService nameServiceValue, IISBNService isbnServiceValue, IPriceService priceServiceValue){nameService= nameServiceValue;isbnService= isbnServiceValue;priceService= priceServiceValue;InitItems();}private void InitItems(){BooksCollection=new ObservableCollection<Book>();for (int i = 0; i<100; i++){BooksCollection.Add(new Book(){Name=nameService.GetName(),ISBN=isbnService.GetISBN(),Price=priceService.GetPrice()});}}[ObservableProperty]private ObservableCollection<Book> booksCollection;[ObservableProperty]private double gridWidth;[ObservableProperty]private double gridHeight;}public class Book{public string Name { get; set; }public string ISBN { get; set; }public decimal Price { get; set; }}public interface INameService{string GetName();}public class NameService : INameService{int idx = 0;public string GetName(){return $"Name_{Interlocked.Increment(ref idx)}";}}public interface IISBNService{string GetISBN();}public class ISBNService : IISBNService{int idx = 0;public string GetISBN(){return $"ISBN_{Interlocked.Increment(ref idx)}_{Guid.NewGuid():N}";}}public interface IPriceService{decimal GetPrice();}public class PriceService : IPriceService{Random rnd = new Random();public decimal GetPrice(){return (decimal)rnd.NextDouble()*100;}}}

 

 

 

 

 

 

 

 

 

 

 

image

 

 

 

 

image

 

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

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

相关文章

完整教程:从“我店”模式看绿色积分电商平台的困境与破局

完整教程:从“我店”模式看绿色积分电商平台的困境与破局pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consola…

Java第三周课前思考

什么样的方法应该用static修饰?不用static修饰的方法往往具有什么特性?Student的getName应该用static修饰吗?完成独立功能或创建类的实例或对类级别的属性进行操作的方法应该用static修饰。 不用static修饰的方法往…

完整教程:光伏电站安全 “守护神”:QB800 绝缘监测平台,为清洁能源高效运行筑固防线

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

Java的安装及卸载

卸载JDK删除java的安装目录 删除JAVA_HOME(环境配置中) 删除path下关于java的目录(环境配置中) cmd中查找java -version是否仍存在安装JDK百度搜索JDK8,找到下载地址 同意协议 下载电脑对应的版本 双击安装JDK 记…

sql server 折腾时不小心去掉了 sysadmin 权限

sql server 折腾时不小心去掉了 sysadmin 权限恢复方法: net stop MSSQLSERVERsqlcmd -E -S . -Q "ALTER SERVER ROLE sysadmin ADD MEMBER [MyPC\admin]"net start MSSQLSERVER桂棹兮兰桨,击空明兮溯流光…

题解:P13882 [蓝桥杯 2023 省 Java A] 小蓝的旅行计划

挺可爱的反悔贪心,乍一看没看出和旅行家的预算的区别,甚至做完才发现不一样的说。 正文 首先我们可以将操作分为两个部分。分别是用油操作和加油操作。 用油 有一个简单的贪心策略,用油的时候首先使用最便宜的油,这…

深入解析:无人设备遥控器之帧同步技术篇

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

实用指南:订阅式红队专家服务:下一代网络安全评估新模式

实用指南:订阅式红队专家服务:下一代网络安全评估新模式pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consola…

更快的布尔矩阵乘法

这是小蝴蝶研读的第二篇论文,时间复杂度的话,原论文写的是 \(\frac{n^3}{2^{\Omega(\sqrt[7]{\log n})}}\),我感觉这个界可以精确分析出来,不过我还没看懂论文,先占个坑。

RWA技术规范解读:如何实现现实世界资产的合规代币化

RWA技术规范解读:如何实现现实世界资产的合规代币化 近日,深圳市信息服务业区块链协会发布了《RWA技术规范》(T/SZBA-2025),这是国内首个针对现实世界资产代币化的团体标准。本文将深入解读该规范的核心内容,帮助读…

实用指南:Java 集合解析

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

干货预警!Apache SeaTunnel 助力多点 DMALL 构建数据集成平台,探索AI新零售行业应用!

🎉亲爱的社区朋友们,数据集成领域的一场知识盛宴即将来袭!9 月 30 日下午 2 点,Apache SeaTunnel 社区精心策划的又一场线上 Meetup 将准时与大家云端相见!🎉亲爱的社区朋友们,数据集成领域的一场知识盛宴即将…

Apache SeaTunnel 2.3.12 发布!核心引擎升级、连接器生态再扩张

近期,Apache SeaTunnel 2.3.12 正式发版。这是继 2.3.11 之后的又一次迭代,本周期合并 82 个 PR,提供 9 项新特性、30+ 项功能增强、20+ 处文档修正,并修复 43 个 Bug。核心改进集中在 SensorsData 与 Databend 生…

详细介绍:对于牛客网—语言学习篇—C语言入门—链表的题目解析

详细介绍:对于牛客网—语言学习篇—C语言入门—链表的题目解析pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Co…

安全认证哪家强?CISP和HCIE我选...... - 详解

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

Day17Arrays类的初步认识

package com.cc.array;import java.util.Arrays;public class ArrayDem6 {public static void main(String[] args) {int[] a = {12, 3, 43, 4, 235, 5, 6, 45, 7, 7};System.out.println(a);//[I@f6f4d33//打印数组元…

小学生模拟赛题解

A 正常做这题显然 \(10^{18}\) 是不可做的,所以问题一定出现在 gen 上。 注意到 \(7\mid2009\),换句话说,若 \(t_1=3k(k\in\mathbb N_+)\),那么 \(t_2=t_1+9\),这就导致 \(3\mid t_2\)。以此类推,会发现对于 \(\…

服务器安装docker、mysql、redis、nginx、nacos、jdk等

一、安装docker 1.1、安装必要工具 sudo yum install -y yum-utils \ device-mapper-persistent-data \ lvm21.2、进行仓库源设置 sudo yum-config-manager \ --add-repo \ https://mirrors.tuna.tsinghua.edu.cn/dock…

StringComparer.OrdinalIgnoreCase

StringComparer.OrdinalIgnoreCase 是 .NET 提供的不区分大小写、且按 Unicode 码位排序的字符串比较器,适用于哈希表、字典、集合、排序等需要显式指定比较规则的地方。1. 核心特点特性说明比较规则 不区分大小写(A…

LLM大模型:Qwen3-Next-80B中的next究竟是个啥?

1、近期,国内LLM头号玩家阿里发布了Qwen3-Next-80B模型,但从名字上看就和其之前发布的模型不同:多了next!这就奇怪了:为啥会多出一个next?这个next究竟是啥意思了?2、自从3年前 chatGPT 3.5发布后,AI又开始大火…