惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
F
Full Disclosure
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
博客园_首页
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
有赞技术团队
有赞技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
量子位
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
N
News and Events Feed by Topic
罗磊的独立博客
T
Threat Research - Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
Security @ Cisco Blogs
O
OpenAI News
AI
AI
S
Securelist
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题

博客园 - FredGrit

WPF ContentControl invoke Template from resource, reuse datatemplate WPF deserialize xml string as List via [XmlRoot] and [XmlElement] attribute WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List WPF two separated datagrid scroll synchronously both in horizontal and vertical via behavior WPF ContentControl Template is ControlTemplate, ContentTemplate is DataTemplate and must assign value to Content explicitly WPF TreeView show WCF config file WPF itemscontrol loaded downloaded data from WCF via httpclient WPF TreeView HierarchicalDataTemplate DataTemplate, Enum get enum name WPF consume xml generated by WCF , C# deserialize xml to List WPF implemented ICommand and IDisposable WPF ContextMenu,MenuItem command can binding to datacontext's command directly WPF usercontrol pass contextmenu command via implemented Freezable class which does not attach on Visual tree, then invoked in caller MVVM WPF consume data generate by WCF and save via ContextMenu Command in MVVM C# export List<T> to excel file via EPPlus WPF ContextMenu does not rely on host visual tree, the Freezable can exist independently, convey dependency property in usercontrol to caller C# JsonConvert DeserializeObject MissingMemberHandling.Ignore when the source model is completed and the required is partial Freezable objects do not require attachment to the WPF visual tree, maintain a persistent lifetime, and serve as a reliable binding relay between a detached ContextMenu and its parent host control. C# run httplistener to act as service application asynchronously in console, semaphoreslim allow the max concurrent number WPF Microsoft.Xaml.Behaviors.WPF, EventTrigger EventName="PreviewMouseDown" the tunnel event, while the MouseDown can't trigger the command because it was swallowed WPF customize command implemented ICommand, volatile read method is thread safe, preventing cpu and comipler reorder and optimization. WPF ItemsControl load huge 50M+ data WPF consume data generated by WCF periodically in json format WPF customize command based on ICommand and manually trigger WPF consume data generated by grpc services C# produce and consume data via Google.Protobuf WCF produce message and WPF consume periodically via DispatcherTimer WCF deconstruct WebConfig includes bindings, behaviors, service, endpoint ,serviceHostingEnvironment C# insert data into SQLite in batch periodically WPF SQLite SQLiteStudio WPF customize MultiSelectComboBox based on combobox WPF DataGrid Context menu binding command and commandparameter to datacontext WCF set fixed port as http://localhost:8888/ via Project /Properties/web/project url to create virtual directory WPF customize datagrid behavior based on behavior&lt;datagrid&gt; with command and command parameter WPF Microsoft Visual Studio XAML designer is busy WCF WebHttpBinding support both http and https WCF support basicHttpBinding and webHttpBinding - FredGrit WCF TestClient set fixed configuration file WPF consume http json and update periodically via DispatcherTimer WPF render periodically via DispatcherTimer, customize behavior - FredGrit Python cosume WCF service via requests in json format WPF call webHttpBinding from WCF WCF binding webHttpBinding is used to web browser in json format both in request and response WPF invoke WCF dll periodically via DispatcherTimer WCF webHttpBinding is open for web browser and wpf WPF DataTemplateSelector WPF DataGrid customize behavior with multiple commands and command parameters then invoke in mvvm WPF DataGrid behavior customize command and command parameter then invoke and implemented in MVVM WPF ItemsControl customize behavior and save all items WCF service can be accessed by browser WPF WCF produce data as service and WPF consume data as client periodically WPF GRPC and Probuf generated data as service then consume by wpf periodically WPF customize behavior based on Microsoft.Xaml.Behaviors.Wpf with command and commandparameter WPF call data from CPP wrapper dll via CLI\CLR - FredGrit WPF customize behavior WPF get gpu information via System.Management WPF ItemsControl IsItemsHost=True WPF Customize behavior and dependency property command C# Serilog, Serilog.Sinks.Console, Serilog.Sinks.File C# Serilog both in file and console Windows powershell view huge file via command C# serialize huge data more than 100M via splitting into batch and concatenating as one big json file WPF WeakReference C# serialize datetime then deserialize, print lose precision. resolve by ToString(&quot;o&quot;) C# produce data and send via WebSocket as service, Python,Flask,HTML as consumer invoke periodically C# write generated data service and sent via websocket, then consume by python periodically C# DateTime print precision to microseconds C# WebSocket console as service provide data, another console as client,send request periodically C# WebAPI [HttpGet(&quot;{cnt}&quot;] pass argument WPF implement ICommand with async execute WPF ListBox control virtualization in mvvm WPF Data Source invoke from web api C# WebAPI
WPF Prism.Core version 9.0.537 implemented navigation register singleton with splash screen, pass global variable via RegisterSingleton method
FredGrit · 2026-05-13 · via 博客园 - FredGrit
Install-Package Prism.Core -v 9.0.537
Install-Package Prism.Wpf -v 9.0.537
Install-Package Prism.DryIoc -v 9.0.537
<prism:PrismApplication x:Class="WpfApp29.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             ShutdownMode="OnExplicitShutdown">
    <prism:PrismApplication.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
        </Style>
    </prism:PrismApplication.Resources>
</prism:PrismApplication>

using Prism.DryIoc;
using Prism.Ioc;
using System.Windows;
using WpfApp29.ViewModels;
using WpfApp29.Views;

namespace WpfApp29
{
    public partial class App : PrismApplication
    {
        public App()
        {
            Application.Current.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var splash = new SplashWin();
            splash.ShowDialog();
            base.OnStartup(e);
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        protected override Window CreateShell()
        {
            return new MainWin();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<BooksViewModel>();
            //containerRegistry.RegisterForNavigation<MainWin,MainWinViewModel>();
            containerRegistry.RegisterForNavigation<Books, BooksViewModel>("Books");            
            containerRegistry.RegisterForNavigation<AddBook, AddBookViewModel>("AddBook");
            containerRegistry.RegisterForNavigation<EditBooks, EditBooksViewModel>("EditBook");
        }

        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;

namespace WpfApp29.ViewModels
{
    public class MainWinViewModel : BindableBase
    {
        private IRegionManager regionManager;
        private BooksViewModel booksVM;
        public DelegateCommand ViewBooksCommand => new DelegateCommand(ViewBooksCommandExecuted);
        public DelegateCommand AddBookCommand => new DelegateCommand(AddBookCommandExecuted);
        public DelegateCommand EditBookCommand => new DelegateCommand(EditBookCommandExecuted);

        private void AddBookCommandExecuted()
        {
            Navigate("AddBook");
        }

        private void EditBookCommandExecuted()
        {
            if(booksVM.SelectedBk==null)
            {
                MessageBox.Show("No book selected");
                return;
            }
            Navigate("EditBook");
        }

        private void ViewBooksCommandExecuted()
        {
            Navigate("Books");
        }

        public MainWinViewModel(IRegionManager regionManagerValue,BooksViewModel bookVMValue)
        {
            regionManager = regionManagerValue;
            booksVM = bookVMValue;
            NavigateOnLoaded();
        }

        private async void NavigateOnLoaded()
        {
            await Task.Delay(1);
            Navigate("Books");
        }

        private void Navigate(string viewName)
        {
            regionManager.RequestNavigate("ContentRegion", viewName);
        }
    }
}
//D:\C\WpfApp29\WpfApp29\App.xaml
<prism:PrismApplication x:Class="WpfApp29.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             ShutdownMode="OnExplicitShutdown">
    <prism:PrismApplication.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
        </Style>
    </prism:PrismApplication.Resources>
</prism:PrismApplication>

//D:\C\WpfApp29\WpfApp29\App.xaml.cs
using Prism.DryIoc;
using Prism.Ioc;
using System.Windows;
using WpfApp29.ViewModels;
using WpfApp29.Views;

namespace WpfApp29
{
    public partial class App : PrismApplication
    {
        public App()
        {
            Application.Current.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var splash = new SplashWin();
            splash.ShowDialog();
            base.OnStartup(e);
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        protected override Window CreateShell()
        {
            return new MainWin();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<BooksViewModel>();
            //containerRegistry.RegisterForNavigation<MainWin,MainWinViewModel>();
            containerRegistry.RegisterForNavigation<Books, BooksViewModel>("Books");            
            containerRegistry.RegisterForNavigation<AddBook, AddBookViewModel>("AddBook");
            containerRegistry.RegisterForNavigation<EditBooks, EditBooksViewModel>("EditBook");
        }

        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
        }
    }
}

//D:\C\WpfApp29\WpfApp29\Views\SplashWin.xaml
<Window x:Class="WpfApp29.Views.SplashWin"
        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:WpfApp29.Views"
        mc:Ignorable="d"
        Title="SplashWin" WindowState="Maximized">
    <Grid>
        <Grid 
                MouseDown="Button_Click">
            <Grid.Background>
                <ImageBrush ImageSource="pack://application:,,,/WpfApp29;component/Resources/Images/333.jpg" />
            </Grid.Background>
        </Grid>
    </Grid>
</Window>

//D:\C\WpfApp29\WpfApp29\Views\SplashWin.xaml.cs
using System;
using System.Collections.Generic;
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.Shapes;

namespace WpfApp29.Views
{
    /// <summary>
    /// Interaction logic for SplashWin.xaml
    /// </summary>
    public partial class SplashWin : Window
    {
        public SplashWin()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //DialogResult = true;
            this.Close();
        }
    }
}

//D:\C\WpfApp29\WpfApp29\Views\MainWin.xaml <Window x:Class="WpfApp29.Views.MainWin" 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:WpfApp29.Views" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d" Title="MainWin" WindowState="Maximized"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10" HorizontalAlignment="Left"> <Button Content="BooksView" Command="{Binding ViewBooksCommand}" Margin="5"/> <Button Content="Add Book" Command="{Binding AddBookCommand}" Margin="5"/> <Button Content="Edit Book" Command="{Binding EditBookCommand}" Margin="5"/> </StackPanel> <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" Margin="10"/> </Grid> </Window> //D:\C\WpfApp29\WpfApp29\ViewModels\MainWinViewModel.cs using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace WpfApp29.ViewModels { public class MainWinViewModel : BindableBase { private IRegionManager regionManager; private BooksViewModel booksVM; public DelegateCommand ViewBooksCommand => new DelegateCommand(ViewBooksCommandExecuted); public DelegateCommand AddBookCommand => new DelegateCommand(AddBookCommandExecuted); public DelegateCommand EditBookCommand => new DelegateCommand(EditBookCommandExecuted); private void AddBookCommandExecuted() { Navigate("AddBook"); } private void EditBookCommandExecuted() { if(booksVM.SelectedBk==null) { MessageBox.Show("No book selected"); return; } Navigate("EditBook"); } private void ViewBooksCommandExecuted() { Navigate("Books"); } public MainWinViewModel(IRegionManager regionManagerValue,BooksViewModel bookVMValue) { regionManager = regionManagerValue; booksVM = bookVMValue; NavigateOnLoaded(); } private async void NavigateOnLoaded() { await Task.Delay(1); Navigate("Books"); } private void Navigate(string viewName) { regionManager.RequestNavigate("ContentRegion", viewName); } } } //D:\C\WpfApp29\WpfApp29\Views\AddBooks.xaml <UserControl x:Class="WpfApp29.Views.AddBook" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Id:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding NewBook.Id}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Name:"/> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding NewBook.Name}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="ISBN:"/> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding NewBook.ISBN}"/> <Button Grid.Row="3" Grid.Column="0" Content="Cancel" Command="{Binding CancelCommand}"/> <Button Grid.Row="3" Grid.Column="1" Content="Save" Command="{Binding SaveCommand}"/> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\AddBookViewModel.cs using System; using System.Collections.Generic; using System.Text; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class AddBookViewModel : BindableBase,INavigationAware { private BooksViewModel booksVM; public DelegateCommand CancelCommand => new DelegateCommand(CancelCommandExecuted); public DelegateCommand SaveCommand => new DelegateCommand(SaveCommandExecuted); public AddBookViewModel(BooksViewModel booksVMValue) { booksVM = booksVMValue; InitNewBook(); } private void CancelCommandExecuted() { return; } private void SaveCommandExecuted() { if (NewBook != null && NewBook.Id > 0) { booksVM.BooksCollection.Add(NewBook); } InitNewBook(); } public void OnNavigatedTo(NavigationContext navigationContext) { InitNewBook(); } private void InitNewBook() { NewBook = new Book(); var lastBk = booksVM.BooksCollection.LastOrDefault(); NewBook.Id = lastBk != null ? lastBk.Id + 1 : 1; } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { } private Book newBook; public Book NewBook { get { return newBook; } set { SetProperty(ref newBook, value); } } } } //D:\C\WpfApp29\WpfApp29\Views\Books.xaml <UserControl x:Class="WpfApp29.Views.Books" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <DataGrid ItemsSource="{Binding BooksCollection}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.CacheLength="2,2" VirtualizingPanel.CacheLengthUnit="Item" EnableColumnVirtualization="True" EnableRowVirtualization="True" ScrollViewer.CanContentScroll="True" ScrollViewer.IsDeferredScrollingEnabled="True" SnapsToDevicePixels="True" UseLayoutRounding="True" AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True" SelectionMode="Single" SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <DataGrid.Resources> <Style TargetType="DataGridRow"> <Setter Property="FontSize" Value="30"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="FontSize" Value="50"/> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> </Style> </DataGrid.Resources> </DataGrid> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\BooksViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; using System.Printing; using System.Text; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class BooksViewModel : BindableBase { private static long idx = 0; private static readonly object objLock = new object(); private static long GetIdx() { return Interlocked.Increment(ref idx); } public BooksViewModel() { InitBooksCollection(); } private void InitBooksCollection() { BooksCollection = new ObservableCollection<Book>(); for (int i = 0; i < 100; i++) { var a = GetIdx(); BooksCollection.Add(new Book() { Id = a, Name = $"Name_{a}", ISBN = $"ISBN_{a}_{Guid.NewGuid():N}" }); } } private ObservableCollection<Book> booksCollection; public ObservableCollection<Book> BooksCollection { get { return booksCollection; } set { SetProperty(ref booksCollection, value); } } private Book selectedBk; public Book SelectedBk { get { return selectedBk; } set { SetProperty(ref selectedBk, value); } } } } //D:\C\WpfApp29\WpfApp29\Views\EditBooks.xaml <UserControl x:Class="WpfApp29.Views.EditBooks" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Id:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding SelectedBook.Id, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Name:"/> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedBook.Name, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="ISBN:"/> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectedBook.ISBN, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <Button Grid.Row="3" Grid.Column="0" Content="Cancel" Command="{Binding CancelCommand}"/> <Button Grid.Row="3" Grid.Column="1" Content="Update" Command="{Binding UpdateCommand}"/> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\EditBooksViewModel.cs using System; using System.Collections.Generic; using System.Text; using System.Windows; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class EditBooksViewModel : BindableBase, INavigationAware { public DelegateCommand CancelCommand { get; set; } public DelegateCommand UpdateCommand { get; set; } private BooksViewModel booksVM; public EditBooksViewModel(BooksViewModel booksVMValue) { CancelCommand = new DelegateCommand(CancelCommandExecuted); UpdateCommand = new DelegateCommand(UpdateCommandExecuted); booksVM= booksVMValue; SelectedBook = booksVM.SelectedBk; } private void UpdateCommandExecuted() { int selectedIdx = booksVM.BooksCollection.IndexOf(SelectedBook); if(selectedIdx>=0) { booksVM.BooksCollection.RemoveAt(selectedIdx); booksVM.BooksCollection.Insert(selectedIdx, SelectedBook); MessageBox.Show($"{DateTime.Now},update BookId:{SelectedBook.Id} successfully"); } } private void CancelCommandExecuted() { return; } public void OnNavigatedTo(NavigationContext navigationContext) { SelectedBook = booksVM.SelectedBk; } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { } private Book selectedBook; public Book SelectedBook { get { return selectedBook; } set { SetProperty(ref selectedBook, value); } } } }

image

image

image

image

image

image

image