WPF viewmodel retrieve matched view /window

news/2025/9/19 20:08:10/文章来源:https://www.cnblogs.com/Fred1987/p/19101602
private Window? GetWindow()
{foreach (Window win in Application.Current.Windows){if (win.DataContext==this){return win;}}return null;
}

 

 

Install-Package CommunityToolkit.mvvm;
Install-Package Micorosoft.Extensions.DependencyInjection;

 

 

 

//app.xaml
<Application x:Class="WpfApp28.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp28"><Application.Resources></Application.Resources>
</Application>//app.xaml.cs
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Windows;namespace WpfApp28
{/// <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 static void ConfigureServices(ServiceCollection services){services.AddSingleton<IIDService, IDService>();services.AddSingleton<INameService, NameService>();services.AddSingleton<IISBNService, ISBNService>();services.AddSingleton<MainVM>();services.AddSingleton<MainWindow>();}protected override void OnExit(ExitEventArgs e){base.OnExit(e);serviceProvider?.Dispose();}}}//mainwindow.xaml
<Window x:Class="WpfApp28.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:WpfApp28"WindowState="Maximized"mc:Ignorable="d"Title="{Binding StatusMsg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="450" Width="800"><Grid><ListBoxItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsVirtualizing="True"VirtualizingPanel.VirtualizationMode="Recycling"ScrollViewer.IsDeferredScrollingEnabled="True"><ListBox.ItemTemplate><DataTemplate><Grid       Width="{Binding DataContext.GridWidth,RelativeSource={RelativeSource AncestorType=Window}}"Height="{Binding DataContext.GridHeight,RelativeSource={RelativeSource AncestorType=Window}}"><Grid.Background><ImageBrush ImageSource="{Binding ImgSource}"/></Grid.Background><Grid.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="30"/><Setter Property="HorizontalAlignment" Value="Center"/><Setter Property="VerticalAlignment" Value="Center"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="FontSize" Value="50"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style></Grid.Resources><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/></Grid.RowDefinitions><TextBlock Text="{Binding Id}" Grid.Column="0" Grid.Row="0"/><TextBlock Text="{Binding Name}" Grid.Column="1" Grid.Row="0"/><TextBlock Text="{Binding ISBN}" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1"/></Grid></DataTemplate></ListBox.ItemTemplate></ListBox>         </Grid>
</Window>//window.xaml.cs
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
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;namespace WpfApp28
{/// <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;this.Loaded+=async (s, e) =>{await LoadDataAsync();};}private async Task LoadDataAsync(){if (DataContext is MainVM vm){await vm.InitDataAsync();}}private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e){if (DataContext is MainVM vm){var fe = this.Content as FrameworkElement;if (fe==null){return;}vm.GridWidth=fe.ActualWidth;vm.GridHeight=fe.ActualHeight/2;}}}public partial class MainVM : ObservableObject{IIDService idService;INameService nameService;IISBNService isbnService;private Stopwatch watch;public MainVM(IIDService idServiceValue,INameService nameServiceValue,IISBNService isbnServiceValue){idService=idServiceValue;nameService=nameServiceValue;isbnService=isbnServiceValue;watch=Stopwatch.StartNew();}private void InitVisualTreesList(){VisualChildrenCollection=new ObservableCollection<string>();Window mainWin = GetWindow();if (mainWin!=null){var visualsList = GetVisualChildren<Visual>(mainWin);foreach (var visual in visualsList){VisualChildrenCollection.Add(visual.GetType().Name);}}string visualChildrenStr = string.Join("\n", VisualChildrenCollection.ToArray());Debug.WriteLine($"Visual Tree children:\n{visualChildrenStr}\n\n\n");}public async Task InitDataAsync(){string imgDir = @"../../../Images";if (!Directory.Exists(imgDir)){return;}var imgs = Directory.GetFiles(imgDir);if (imgs==null ||!imgs.Any()){return;}int imgsCount = imgs.Count();BooksCollection=new ObservableCollection<Book>();List<Book> booksList = new List<Book>();await Task.Run(async () =>{for (int i = 0; i<1000001; i++){booksList.Add(new Book(){Id=idService.GetID(),Name=nameService.GetName(),ISBN=isbnService.GetISBN(),ImgSource=GetImgSourceViaUrl(imgs[i%imgsCount])});if (i<1000&& i%100==0){await PopulateBooksCollectionAsync(booksList);}else if (i>=1000 && i%1000000==0){await PopulateBooksCollectionAsync(booksList);}}if (booksList.Any()){await PopulateBooksCollectionAsync(booksList);}});InitVisualTreesList();InitLogicalTreesList();}private void InitLogicalTreesList(){Window mainWin = GetWindow();var logicalChildren = GetAllLogicalChildren(mainWin);string logicalTreesStr = string.Join("\n", logicalChildren.Select(x => x.GetType().Name));Debug.WriteLine(logicalTreesStr);}private ImageSource GetImgSourceViaUrl(string imgUrl){BitmapImage bmi = new BitmapImage();bmi.BeginInit();bmi.UriSource=new Uri(imgUrl, UriKind.RelativeOrAbsolute);bmi.CacheOption=BitmapCacheOption.OnDemand;bmi.EndInit();bmi.Freeze();return bmi;}private async Task PopulateBooksCollectionAsync(List<Book> booksList){var tempList = booksList.ToList();booksList.Clear();await Application.Current.Dispatcher.InvokeAsync(() =>{foreach (var bk in tempList){BooksCollection.Add(bk);}StatusMsg=$"Loaded {BooksCollection.Count} items,{GetMemory()},{GetTimeCost()}";}, System.Windows.Threading.DispatcherPriority.Background);}private string GetMemory(){var procMemory = Process.GetCurrentProcess().PrivateMemorySize64/1024.0d/1024.0d;return $"Memory:{procMemory.ToString("#,##0.00")} M";}private string GetTimeCost(){return $"Time cost: {watch.Elapsed.TotalSeconds} seconds";}private static IEnumerable<T> GetVisualChildren<T>(DependencyObject parent) where T : DependencyObject{if (parent == null){yield break;}int childrenCount = VisualTreeHelper.GetChildrenCount(parent);for (int i = 0; i<childrenCount; i++){DependencyObject child = VisualTreeHelper.GetChild(parent, i);if (child is T tChild){yield return tChild;}foreach (var descedant in GetVisualChildren<T>(child)){yield return descedant;}}}public static IEnumerable<DependencyObject> GetAllLogicalChildren(DependencyObject parent){if (parent == null){yield break;}foreach (var child in LogicalTreeHelper.GetChildren(parent)){if (child is DependencyObject depChild){yield return depChild;// Recurse down into this child's childrenforeach (var descendant in GetAllLogicalChildren(depChild)){yield return descendant;}}}}private Window? GetWindow(){foreach (Window win in Application.Current.Windows){if (win.DataContext==this){return win;}}return null;}[ObservableProperty]private double gridWidth;[ObservableProperty]private double gridHeight;[ObservableProperty]private ObservableCollection<Book> booksCollection;[ObservableProperty]private string statusMsg;[ObservableProperty]private ObservableCollection<string> visualChildrenCollection;}public class Book{public int Id { get; set; }public string Name { get; set; }public string ISBN { get; set; }public ImageSource ImgSource { get; set; }}public interface IIDService{int GetID();}public class IDService : IIDService{int id = 0;public int GetID(){return Interlocked.Increment(ref id);}}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}";}}
}

 

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

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

相关文章

实用指南:目标检测如何将同时有方形框和旋转框的json/xml标注转为txt格式

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

ctfshow web351

<font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">curl_init()</font>:初始curl会话 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 24…

ctfshow web353

<?php error_reporting(0); highlight_file(__FILE__); $url=$_POST[url]; $x=parse_url($url); if($x[scheme]===http||$x[scheme]===https){ if(!preg_match(/localhost|127\.0\.|\。/i, $url)){ $ch=curl_init(…

fxztgxj5.dll fxzrs4qj.dll fxztgxa5.dll fxzrs3qj.dll fxzpmc1.dll fxzrs2qj.dll fxzmpxa5.dll - 实践

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

Linux虚拟机常用命令与Hadoop生态组件启动大全

本文将分为两部分,第一部分整理Linux虚拟机下的高频操作命令(文件编辑、解压、拷贝等),第二部分汇总Hadoop, Zookeeper, HBase, Hive等组件的启动/停止命令,方便随时查阅。 第一部分:Linux虚拟机高频操作命令 1.…

测试新手必学:10个让Bug无处遁形的黑盒测试技巧

在软件开发的世界中,测试是确保产品质量的重要环节。对于刚踏入测试领域的新手来说,掌握有效的测试方法至关重要。在众多测试方法中,黑盒测试因其独特的优势备受青睐。它不需要测试人员了解代码内部实现,而是专注于…

private void Form1_Load与构造方法前执行顺序

Form1_Load 事件是在 构造方法之后,窗体初始化之后 执行的。也就是说,Form1_Load 事件发生在窗体构造方法执行之后,但在窗体完全显示之前。 窗体的初始化顺序 构造函数:Form1 的构造方法会首先执行,构造方法中通常…

数据分类分级如何高效低成本落地?|高效智能的数据分类分级产品推荐(2025)

数据分类分级如何高效低成本落地?|高效智能的数据分类分级产品推荐(2025)在《数据安全法》(第二十一条)与《个人信息保护法》确立分类分级制度框架、并由《网络数据安全管理条例》(2024 年,第五条、第二十九条…

文化课暂时计划

1. 作业完成策略 数学 \(/\) 物理 \(\gt\) 化学 \(\gt\) 英语 \(\gt\) 生物 \(\gt\) 语文 学会的可以适当的抄。 2. 课上效率提升 这一点,我觉得非常重要,课上时间是非常宝贵的,课上效率低下,课下就一定得找时间找…

private void Form1_Load和 private void Form1_Activated 方法区别

orm1_Load 和 Form1_Activated 都是 WinForms 中常见的事件方法,它们在窗体生命周期的不同阶段被触发。虽然它们都与窗体的显示和激活相关,但它们的触发时机和目的有所不同。让我们来具体看看它们的区别:Form1_Load…

HarmonyOS Stage模型与ArkTS:现代应用开发的核心架构与最佳实践 - 详解

HarmonyOS Stage模型与ArkTS:现代应用开发的核心架构与最佳实践 - 详解pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: …

【CV】图像超分辨率的一些基础概念

【CV】图像超分辨率的一些基础概念Posted on 2025-09-19 19:32 SaTsuki26681534 阅读(0) 评论(0) 收藏 举报图像退化模型 在图像超分辨率(Super-Resolution, SR)任务中,退化模型(Degradation Model) 是核心基…

完整教程:苹果WWDC25开发秘技揭秘:SwiftData3如何重新定义数据持久化

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

H5 页面与 Web 页面的制作方法 - 实践

H5 页面与 Web 页面的制作方法 - 实践pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mona…

Python面试题及详细答案150道(116-125) -- 性能优化与调试篇 - 实践

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

完整教程:构建基石:Transformer架构

完整教程:构建基石:Transformer架构2025-09-19 19:21 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !i…

Spring Cloud Gateway吞吐量优化

目录一、网络与容器层面优化二、路由与过滤器优化三、缓存与限流优化四、JVM 与资源优化五、监控与压测验证总结 Spring Cloud Gateway 作为基于 Netty 的异步非阻塞网关,其吞吐量(吞吐量)优化需要从 网络配置、线程…

【先记录一下】windows下使用的lazarus/fpc安装到中文的目录时出错的问题

【先记录一下】windows下使用的lazarus/fpc安装到中文的目录时出错的问题windows下使用的lazarus/fpc安装到中文的目录时出错的问题由以下3个不支持中文引起的:1、make.exe 我使用mingw64带的make.exe替换不支持中…