Calling a C# WPF library from C++
- // ConsoleApplication_Hello.cpp : This file contains the 'main' function. Program execution begins and ends there.
- //
- #include <iostream>
- #include "Windows.h"
- #include <filesystem>
- #include <fstream>
- #include <string>
- #include "combaseapi.h"
- #pragma comment(lib,"..\\x64\\Debug\\ClassLibrary1")
- #define _hr(X) _ASSERTE(SUCCEEDED(X))
- using namespace std;
- namespace fs = std::filesystem;
- fs::path MyRootPath;
- extern "C" __declspec(dllimport)
- HRESULT Get_Load_WPF_Library_Interface(void** pMyObj);
- struct __declspec(dllimport) MyCreateInstance {
- MyCreateInstance();
- HRESULT Create_WPF_Instance(BSTR filename, BSTR CLSID,
- IUnknown** pIUnknown);
- ~MyCreateInstance();
- };
- class MyBSTR
- {
- BSTR _bstr;
- public:
- MyBSTR(std::wstring str)
- {
- _bstr = SysAllocStringLen(str.c_str(), str.length());
- }
- ~MyBSTR() { SysFreeString(_bstr); }
- operator BSTR()const { return _bstr; }
- };
- static void AppInitialize() {
- WCHAR ModuleFileName[MAX_PATH];
- fs::path ModuleFileName_Path;
- if (GetModuleFileNameW(NULL, ModuleFileName, MAX_PATH) > MAX_PATH)
- throw exception("GetModuleFileNameW");
- wcout << "ModuleFileName=\t" << ModuleFileName << endl;
- ModuleFileName_Path = fs::path(ModuleFileName);
- MyRootPath = ModuleFileName_Path.
- parent_path().parent_path().parent_path().parent_path();
- wcout << "MyRootPath=\t" << MyRootPath.wstring() << endl;
- }
- __interface IMyTest : IDispatch {
- HRESULT Hello(INT32 JobID, BSTR MyRootPath);
- };
- void DoMyJob(MyCreateInstance& MyCreateInstanceObj, int JobID) {
- const fs::path WPF_Library_Path =
- L"WpfLibrary_Hello\\WpfLibrary_Hello\\bin\\x64\\Debug\\net9.0-windows\\WpfLibrary_Hello.dll";
- const std::wstring clsid_in_WPF_Library =
- L"{7B3236BC-C3CD-4EC0-85C5-A9EC33C26D7D}";
- const std::wstring IID_IMyTest =
- L"{0A46DC92-73F3-4B6E-AC34-3F9A1396C163}";
- IUnknown* pIUnknown = NULL;
- IMyTest* pIMyTest = NULL;
- fs::path Library_FullPath = MyRootPath / WPF_Library_Path;
- if (!fs::exists(Library_FullPath)) {
- wcerr << Library_FullPath.wstring() << endl;
- throw exception("File not exist");
- }
- _hr(MyCreateInstanceObj.Create_WPF_Instance(
- MyBSTR(Library_FullPath.wstring()),
- MyBSTR(clsid_in_WPF_Library),
- &pIUnknown));
- IID _IID_IMyTest;
- _hr(IIDFromString(IID_IMyTest.c_str(), &_IID_IMyTest));
- _hr(pIUnknown->QueryInterface(_IID_IMyTest, (void**)&pIMyTest));
- MyBSTR My_RootPath(MyRootPath.wstring().append(L"\\"));
- _hr(pIMyTest->Hello(JobID, My_RootPath));
- pIUnknown->Release();
- cout << "pIMyTest->Release() =" << pIMyTest->Release() << endl;
- }
- int main()
- {
- std::cout << "Hello World!\n";
- fs::path Current_Directory = fs::current_path();
- wcout << "CurrentDir =\t" << Current_Directory.wstring() << endl;
- try {
- AppInitialize();
- _hr(CoInitialize(NULL));
- MyCreateInstance MyCreateInstanceObj;
- int MyJobID;
- cout << "Enter a Job id " << endl
- << "1: WpfLibrary_Hello" << endl
- << "2: WpfApp_Hello" << endl;
- cin >> MyJobID;
- if (MyJobID == 1) {
- wcout << endl << L" .\\iisexpress " <<
- L"/path:" << MyRootPath.c_str() << L"\\WpfWebSite_Hello"
- << endl << endl;
- system("Pause");
- }
- DoMyJob(MyCreateInstanceObj, MyJobID);
- CoUninitialize();
- return 0;
- }
- catch (exception ex) {
- cerr << ex.what() << endl;
- return -9;
- }
- }
- #include "pch.h"
- #include "Windows.h"
- #include <iostream>
- #include "ClassLibrary1.h"
- using namespace std;
- #define _hr(X) _ASSERTE(SUCCEEDED(X))
- // {4BC492CD-E50F-426B-AD24-7C9280A5AF1E}
- static const CLSID clsid_Create_WPF_Instance_not_Used =
- { 0x4bc492cd, 0xe50f, 0x426b, { 0xad, 0x24, 0x7c, 0x92, 0x80, 0xa5, 0xaf, 0x1e } };
- // {2FE5D888-1813-4EA9-A1E1-000650359BFC}
- static const IID iid_ICreate_WPF_Instance =
- { 0x2fe5d888, 0x1813, 0x4ea9, { 0xa1, 0xe1, 0x0, 0x6, 0x50, 0x35, 0x9b, 0xfc } };
- extern "C" __declspec(dllexport)
- HRESULT Get_Load_WPF_Library_Interface(void** ppInterface)
- {
- try {
- WpfLibrary_For_Remove_Reference::Class1^ MyWpf_Object =
- gcnew WpfLibrary_For_Remove_Reference::Class1();
- IUnknown* pIunknown = (IUnknown*)
- System::Runtime::InteropServices::Marshal::GetIUnknownForObject(
- MyWpf_Object).ToPointer();
- pIunknown->QueryInterface(iid_ICreate_WPF_Instance,
- ppInterface);
- pIunknown->Release();
- return S_OK;
- }
- catch (const System::Exception^ ex) {
- return -234;
- }
- }
- __interface ICreate_WPF_Instance : IDispatch {
- HRESULT Create_WPF_Instance(BSTR filename, BSTR CLSID,
- IUnknown** pIUnknown);
- };
- static ICreate_WPF_Instance* pICreate_WPF_Instance;
- struct __declspec(dllexport) MyCreateInstance {
- MyCreateInstance()
- {
- _hr(Get_Load_WPF_Library_Interface((void**)&pICreate_WPF_Instance));
- }
- HRESULT Create_WPF_Instance(BSTR filename, BSTR CLSID,
- IUnknown** pIUnknown)
- {
- if (*pIUnknown != NULL)return -44;
- return pICreate_WPF_Instance->Create_WPF_Instance(
- filename, CLSID, pIUnknown);
- }
- ~MyCreateInstance() {
- ULONG RefCout = pICreate_WPF_Instance->Release();
- std::cout << "pICreate_WPF_Instance->Release()=" << RefCout << std::endl;
- pICreate_WPF_Instance = NULL;
- }
- };
- #ifdef IMPORT
- struct __declspec(dllimport) MyCreateInstance {
- MyCreateInstance();
- HRESULT Create_WPF_Instance(BSTR filename, BSTR CLSID,
- IUnknown** pIUnknown);
- ~MyCreateInstance();
- };
- #endif
- using System.Runtime.InteropServices;
- using System.Windows;
- namespace WpfLibrary_For_Remove_Reference
- {
- [Guid(Class1.IID_ICreate_WPF_Instance)]
- [ComVisible(true)]
- public interface ICreate_WPF_Instance
- {
- void Create_WPF_Instance(String filename, String CLSID,
- [MarshalAs(UnmanagedType.IUnknown)] ref Object pIUnknown);
- }
- [Guid(clsid_Create_WPF_Instance)]
- [ClassInterface(ClassInterfaceType.None)]
- [ComVisible(true)]
- public class Class1 : ICreate_WPF_Instance
- {
- public const String clsid_Create_WPF_Instance =
- "4BC492CD-E50F-426B-AD24-7C9280A5AF1E";
- public const String IID_ICreate_WPF_Instance =
- "2FE5D888-1813-4EA9-A1E1-000650359BFC";
- void ICreate_WPF_Instance.Create_WPF_Instance(String filename, String CLSID,
- [MarshalAs(UnmanagedType.IUnknown)] ref Object pIUnknown)
- {
- System.Reflection.Assembly Assembly_Library =
- System.Reflection.Assembly.LoadFrom(filename);
- System.Guid clsid = Guid.Parse(CLSID);
- foreach (System.Type clsid_type in Assembly_Library.GetExportedTypes())
- if (clsid_type.GUID == clsid)
- try
- {
- System.Object? obj = System.Activator.CreateInstance(clsid_type);
- if (obj != null) { pIUnknown = obj; return; }
- }
- catch (System.Exception exc)
- {
- MessageBox.Show(exc.Message);
- throw;
- }
- throw new Exception($"My clsid={CLSID}")
- {
- HResult = -789
- };
- }
- }
- }
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Windows;
- namespace WpfLibrary_Hello
- {
- class MyApp : System.Windows.Application
- {
- }
- [Guid(Class1.IMyTest_IID)]
- [ComVisible(true)]
- public interface IMyTest_WPF
- {
- void Hello(Int32 id, String str);
- }
- [Guid(clsid)]
- [ClassInterface(ClassInterfaceType.None)]
- [ComVisible(true)]
- public partial class Class1 : IMyTest_WPF
- {
- public Class1()
- {
- }
- public const String clsid = "7B3236BC-C3CD-4EC0-85C5-A9EC33C26D7D";
- public const String IMyTest_IID = "0A46DC92-73F3-4B6E-AC34-3F9A1396C163";
- static String My_RootPath = String.Empty;
- static int MyJobID = 0;
- static MyApp? app;
- int hr = 0;
- void IMyTest_WPF.Hello(Int32 id, String myRootPath)
- {
- MyJobID = id;
- My_RootPath = myRootPath;
- try
- {
- DoWorkInSTA(); return;
- /*
- Thread STA_Thread = new Thread(DoWorkInSTA);
- STA_Thread.SetApartmentState(ApartmentState.STA);
- STA_Thread.Start();
- STA_Thread.Join();
- */
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Exception meesage");
- hr = -1;
- }
- if (0 != hr) throw new Exception($"hr={hr}") { HResult = (int)hr };
- }
- [System.STAThreadAttribute()]
- void DoWorkInSTA()
- {
- try
- {
- app ??= new();
- Uri MyStartUp_Uri;
- switch (MyJobID)
- {
- case 1:
- LoadAssembly(
- @"WpfLibrary_Hello\WpfLibrary_Hello\bin\x64\Debug\net9.0-windows\Microsoft.Web.WebView2.Wpf.dll"
- );
- MyStartUp_Uri =
- new Uri(
- @"pack://application:,,,/WpfLibrary_Hello;Component/Page_Home.xaml",
- UriKind.Absolute);
- // @"/WpfLibrary_Hello;Component/Page_Home.xaml",
- // UriKind.Relative);
- break;
- case 2:
- {
- System.Reflection.Assembly[] Ass5 = [
- LoadAssembly(@"WpfApp_Hello\WpfApp_Hello\bin\x64\Debug\net9.0-windows\WpfApp_Hello.dll") ,
- LoadAssembly(@"WpfApp_Hello\WpfApp_Hello\bin\x64\Debug\net9.0-windows\WpfControlLibrary_Hello.dll"),
- LoadAssembly(@"WpfApp_Hello\WpfApp_Hello\bin\x64\Debug\net9.0-windows\WpfCustomControlLibrary_Hello.dll")
- ];
- AddResource(@"/WpfApp_Hello;component/Dictionary1.xaml",
- UriKind.Relative);
- AddResource(@"/WpfApp_Hello;component/Dictionary2.xaml",
- UriKind.Relative);
- AddResource(@"pack://application:,,,/WpfCustomControlLibrary_Hello;component/Themes/Generic.xaml",
- UriKind.Absolute);
- MyStartUp_Uri = new Uri(
- "/WpfApp_Hello;Component/MainWindow.xaml",
- UriKind.Relative);
- }
- break;
- default:
- throw new Exception($"Error : My Job ID is {MyJobID}");
- }
- app.StartupUri = MyStartUp_Uri;
- //MessageBox.Show($"MyJobID = {MyJobID}");
- app.Run();
- hr = 0;
- }
- catch (Exception ex)
- {
- MessageBox.Show($"DoWorkInSTA Exception:\n{ex.Message}");
- hr = -3;
- }
- static Assembly LoadAssembly(string relativePath) =>
- System.Reflection.Assembly.LoadFrom(My_RootPath +
- relativePath) ?? throw new Exception("LoadFrom error");
- static void AddResource(string Uristr, UriKind Uri_Kind)
- {
- app?.Resources.MergedDictionaries.Add(
- new ResourceDictionary()
- {
- Source = new Uri(Uristr, Uri_Kind)
- });
- }
- }
- }
- }
- <Page x:Class="WpfLibrary_Hello.Page_Home"
- 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:WpfLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800"
- Title="Page_Home">
- <Grid Height="300" VerticalAlignment="Top">
- <Button Content="Use new" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Click_Use_new"/>
- <Button Content="use Uri " HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="Click_Use_Uri"/>
- <Button Content="Web View2" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="Click_WebView"/>
- <TextBlock
- Width="350"
- HorizontalAlignment="Center"
- VerticalAlignment="Center">
- <Hyperlink NavigateUri=
- "https://cheninnjer.blogspot.com/2024/09/marshalling.html"
- RequestNavigate="Hyperlink_RequestNavigate">
- Click here to go cheninnjer.blogspot.com about marshalling
- </Hyperlink>
- </TextBlock>
- </Grid>
- </Page>
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for Page_Home.xaml
- /// </summary>
- public partial class Page_Home : Page
- {
- public Page_Home()
- {
- InitializeComponent();
- }
- private void Click_Use_new(object sender, RoutedEventArgs e)
- {
- NavigationService.Navigate(new Page_WebBrowser());
- }
- private void Click_Use_Uri(object sender, RoutedEventArgs e)
- {
- NavigationService.Navigate(
- new Uri(
- "/WpfLibrary_Hello;Component/Page_WebBrowser.xaml",
- UriKind.Relative)
- );
- }
- private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
- {
- Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)
- {
- UseShellExecute = true
- });
- e.Handled = true;
- }
- private void Click_WebView(object sender, RoutedEventArgs e)
- {
- NavigationService.Navigate(
- new Page_WebView());
- }
- }
- }
- <Page x:Class="WpfLibrary_Hello.Page_WebBrowser"
- 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:WpfLibrary_Hello"
- xmlns:Wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800"
- Title="Page_WebBrowser">
- <DockPanel LastChildFill="True">
- <StackPanel Width="100" DockPanel.Dock="Right">
- <Button Height="50"
- Content="GoBack or GoForward"
- Click="Button_Click"/>
- <TextBlock Height="420" x:Name="MyTextBlock"/>
- </StackPanel>
- <WebBrowser DockPanel.Dock="Left"
- x:Name="webBrowser1"
- Source="http://localhost:8080"/>
- </DockPanel>
- </Page>
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- namespace WpfLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for Page_WebBrowser.xaml
- /// </summary>
- /*
- EXTERN_C const IID IID_IWebBrowserApp;
- #if defined(__cplusplus) && !defined(CINTERFACE)
- MIDL_INTERFACE("0002DF05-0000-0000-C000-000000000046")
- IWebBrowserApp : public IWebBrowser
- {
- public:
- virtual HRESULT STDMETHODCALLTYPE Quit(void) = 0;
- virtual HRESULT STDMETHODCALLTYPE ClientToWindow(
- __RPC__inout int* pcx,
- __RPC__inout int* pcy) = 0;
- virtual HRESULT STDMETHODCALLTYPE PutProperty(
- __RPC__in BSTR Property,
- VARIANT vtValue) = 0;
- virtual HRESULT STDMETHODCALLTYPE GetProperty(
- __RPC__in BSTR Property,
- __RPC__out VARIANT *pvtValue) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_Name(
- __RPC__deref_out_opt BSTR *Name) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_HWND(
- __RPC__out SHANDLE_PTR *pHWND) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_FullName(
- __RPC__deref_out_opt BSTR *FullName) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_Path(
- __RPC__deref_out_opt BSTR *Path) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_Visible(
- __RPC__out VARIANT_BOOL *pBool) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_Visible(
- VARIANT_BOOL Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_StatusBar(
- __RPC__out VARIANT_BOOL *pBool) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_StatusBar(
- VARIANT_BOOL Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_StatusText(
- __RPC__deref_out_opt BSTR *StatusText) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_StatusText(
- __RPC__in BSTR StatusText) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_ToolBar(
- __RPC__out int* Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_ToolBar(
- int Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_MenuBar(
- __RPC__out VARIANT_BOOL *Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_MenuBar(
- VARIANT_BOOL Value) = 0;
- virtual HRESULT STDMETHODCALLTYPE get_FullScreen(
- __RPC__out VARIANT_BOOL *pbFullScreen) = 0;
- virtual HRESULT STDMETHODCALLTYPE put_FullScreen(
- VARIANT_BOOL bFullScreen) = 0;
- };
- */
- /*
- #if defined(__cplusplus) && !defined(CINTERFACE)
- MIDL_INTERFACE("6d5140c1-7436-11ce-8034-00aa006009fa")
- IServiceProvider : public IUnknown
- {
- public:
- virtual HRESULT STDMETHODCALLTYPE QueryService(
- [annotation][in] _In_ REFGUID guidService,
- [annotation][in] _In_ REFIID riid,
- [annotation][out] _Outptr_ void** ppvObject) = 0;
- };
- */
- [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
- [Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
- internal interface IServiceProvider
- {
- [return: MarshalAs(UnmanagedType.IUnknown)]
- object QueryService(ref Guid serviceGuid, ref Guid riid);
- }
- public partial class Page_WebBrowser : Page
- {
- static readonly StringBuilder MyTrace = new();
- static int Count;
- public Page_WebBrowser()
- {
- // MessageBox.Show("1");
- try
- {
- InitializeComponent();
- MyInitilize(webBrowser1);
- }
- catch (Exception ex)
- {
- MessageBox.Show($"{ex.Message}", "InitializeComponent error");
- }
- }
- void MyInitilize(WebBrowser MyWebBrowser)
- {
- try
- {
- MyTrace.Clear();
- MyTrace.AppendLine("Page_WebBrowser 1");
- var IserviceProvider =
- (IServiceProvider)MyWebBrowser.Document
- ?? throw new Exception("IserviceProvider == null");
- Guid IID_IWebBrowserApp = new("0002DF05-0000-0000-C000-000000000046");
- Guid IID_WebBrowser = typeof(SHDocVw.WebBrowser).GUID;
- var IwebBrower = (SHDocVw.WebBrowser)IserviceProvider
- .QueryService(ref IID_IWebBrowserApp, ref IID_WebBrowser)
- ?? throw new Exception("IwebBrower == null");
- IwebBrower.BeforeNavigate2 += DWebBrowserEvents2_BeforeNavigate2EventHandler;
- IwebBrower.NewWindow2 += webBrower1_NewWindow2;
- IwebBrower.OnFullScreen += DWebBrowserEvents2_OnFullScreenEventHandler;
- IwebBrower.DownloadComplete += DWebBrowserEvents2_DownloadCompleteEventHandler;
- IwebBrower.DocumentComplete += DWebBrowserEvents2_DocumentCompleteEventHandler;
- }
- finally
- {
- MyTextBlock.Text = MyTrace.AppendLine("Page_WebBrowser 2").ToString();
- MyTrace.Clear();
- }
- }
- void DWebBrowserEvents2_DownloadCompleteEventHandler()
- {
- MyTrace.AppendLine("Download_Complete");
- }
- void DWebBrowserEvents2_DocumentCompleteEventHandler(
- [In][MarshalAs(UnmanagedType.IDispatch)] object pDisp,
- [In][MarshalAs(UnmanagedType.Struct)] ref object URL)
- {
- MyTrace.AppendLine("Document_Complete");
- }
- void DWebBrowserEvents2_BeforeNavigate2EventHandler(
- [In][MarshalAs(UnmanagedType.IDispatch)] object pDisp,
- [In][MarshalAs(UnmanagedType.Struct)] ref object URL,
- [In][MarshalAs(UnmanagedType.Struct)] ref object Flags,
- [In][MarshalAs(UnmanagedType.Struct)] ref object TargetFrameName,
- [In][MarshalAs(UnmanagedType.Struct)] ref object PostData,
- [In][MarshalAs(UnmanagedType.Struct)] ref object Headers,
- [In][Out] ref bool Cancel)
- {
- MyTrace.AppendLine("BeforeNavigate2");
- }
- void webBrower1_NewWindow2(ref object ppDisp, ref bool Cancel)
- {
- MessageBox.Show("NewWindow2");
- }
- void DWebBrowserEvents2_OnFullScreenEventHandler(
- [In] bool FullScreen)
- {
- MessageBox.Show("OnFullScreenEvent");
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- ((Button)sender).Background = Brushes.Red;
- //MessageBox.Show($"goback={webBrowser1.CanGoBack} goforword={webBrowser1.CanGoForward}");
- if (webBrowser1.CanGoBack)
- {
- MyTrace.AppendLine("1 GoBack");
- webBrowser1.GoBack();
- MyTrace.AppendLine("2 GoBack");
- }
- else if (webBrowser1.CanGoForward)
- {
- MyTrace.AppendLine("1 GoForward");
- webBrowser1.GoForward();
- MyTrace.AppendLine("2 GoForward");
- }
- else
- {
- webBrowser1.Source = new Uri(
- "http://localhost:8080/MyWebPage/HtmlPage1.html");
- }
- MyTextBlock.Text =
- MyTrace.AppendLine($"Button Press {++Count}").ToString();
- MyTrace.Clear();
- }
- }
- }
- <Page x:Class="WpfLibrary_Hello.Page_WebView"
- 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:WpfLibrary_Hello"
- xmlns:Wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800"
- Title="Page_WebView">
- <DockPanel x:Name="MyStackPanel" LastChildFill="True">
- <TextBox x:Name="MyTextBox"
- Text="http://localhost:8080/MyWebPage/HtmlPage2.html"
- Height="30"
- FontSize="22"
- DockPanel.Dock="Top"
- KeyDown="MyTextBox_KeyDown"
- />
- <Wpf:WebView2 x:Name="MyWebView2"
- Source="http://localhost:8080/MyWebPage/HtmlPage2.html"/>
- </DockPanel>
- </Page>
- using Microsoft.Web.WebView2.Core;
- using Microsoft.Web.WebView2.Wpf;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- namespace WpfLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for Page_WebView.xaml
- /// </summary>
- public partial class Page_WebView : Page
- {
- public Page_WebView()
- {
- InitializeComponent();
- MyWebView2.SourceChanged += EventHandlerSourceChange;
- }
- void EventHandlerSourceChange(object? sender, CoreWebView2SourceChangedEventArgs e)
- {
- var s = sender as WebView2;
- //if (e.IsNewDocument)
- MyTextBox.Text = s?.Source.ToString();
- }
- private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.Key == Key.Enter)
- {
- MyWebView2.Source = new Uri(MyTextBox.Text);
- }
- }
- }
- }
- <!DOCTYPE html>
- <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta charset="utf-8" />
- <title></title>
- </head>
- <body>
- <h2>HtmlPage1.html</h2>
- </body>
- </html>
- <!DOCTYPE html>
- <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta charset="utf-8" />
- <title></title>
- </head>
- <body>
- <p id="output-area">Some initial content in HTMLPage2</p>
- <h3>This is HtmlPage2.html </h3>
- <script>
- const TargetElement = document.getElementById("output-area");
- TargetElement.innerHTML = "location path = " +
- window.location.pathname;
- </script>
- </body>
- </html>
- <ResourceDictionary
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:WpfCustomControlLibrary_Hello">
- <Style x:Key="Custom_Button_Chen" TargetType="Button">
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="Button">
- <Grid x:Name="Grid_Chen">
- <Border x:Name="bord_Chen"
- Background="{TemplateBinding Background}"
- BorderBrush="{TemplateBinding BorderBrush}"
- BorderThickness="{TemplateBinding BorderThickness}">
- </Border>
- <ContentPresenter HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>
- <ControlTemplate.Triggers>
- <Trigger Property="IsMouseOver" Value="True" SourceName="Grid_Chen">
- <Setter TargetName="bord_Chen" Property="BorderBrush" Value="Red"/>
- <Setter TargetName="bord_Chen" Property="BorderThickness" Value="8"/>
- <Setter TargetName="bord_Chen" Property="Background" Value="Yellow"/>
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </ResourceDictionary>
- <UserControl x:Class="WpfControlLibrary_Hello.Get_UserControl"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- Height="450" Width="800">
- <Grid>
- <Border x:Name="MyBorder">
- <ListBox SelectionChanged="selectionChange"
- Height="200" Width="300" Foreground="Red" >
- <ListBoxItem>Binding Data Validation</ListBoxItem>
- <ListBoxItem>ListColorNames_class</ListBoxItem>
- <ListBoxItem>ListColorNames_item</ListBoxItem>
- <ListBoxItem>ListColorNames_label</ListBoxItem>
- <ListBoxItem>ListColorNames_string</ListBoxItem>
- <ListBoxItem>NumericUpDown</ListBoxItem>
- </ListBox>
- </Border>
- </Grid>
- </UserControl>
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl1.xaml
- /// </summary>
- public partial class Get_UserControl : UserControl
- {
- public Get_UserControl()
- {
- InitializeComponent();
- }
- void selectionChange(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- MyBorder.Child = listBox.SelectedIndex switch
- {
- 0 => new WpfControlLibrary_Hello.UserControl_Data_Validation(),
- 1 => new WpfControlLibrary_Hello.UserControl_ListColorNames_class(),
- 2 => new WpfControlLibrary_Hello.UserControl_ListColorNames_item(),
- 3 => new WpfControlLibrary_Hello.UserControl_ListColorNames_label(),
- 4 => new WpfControlLibrary_Hello.UserControl_ListColorNames_string(),
- 5 => new WpfControlLibrary_Hello.UserControl_NumericUpDown(),
- _ => throw new ArgumentOutOfRangeException(),
- };
- }
- }
- }
- <Application x:Class="WpfApp_Hello.App"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:WpfApp_Hello"
- StartupUri="MainWindow.xaml">
- <Application.Resources>
- <ResourceDictionary>
- <ResourceDictionary.MergedDictionaries>
- <ResourceDictionary Source="/WpfApp_Hello;component/Dictionary1.xaml"/>
- <ResourceDictionary Source="/WpfApp_Hello;component/Dictionary2.xaml"/>
- <!--
- <ResourceDictionary Source="/HelloWpfCustomControlLibrary;component/Themes/Generic.xaml"/>
- -->
- <ResourceDictionary Source="pack://application:,,,/WpfCustomControlLibrary_Hello;component/Themes/Generic.xaml"/>
- </ResourceDictionary.MergedDictionaries>
- </ResourceDictionary>
- </Application.Resources>
- </Application>
- using System.Windows;
- namespace WpfApp_Hello
- {
- /// <summary>
- /// Interaction logic for App.xaml
- /// </summary>
- public partial class App : Application
- {
- App()
- {
- MyViewModel.Trace.AppendLine("App()");
- }
- protected override void OnStartup(StartupEventArgs e)
- {
- base.OnStartup(e);
- MyViewModel.Trace.AppendLine($"void OnStartup(StartupEventArgs e)");
- }
- protected override void OnExit(ExitEventArgs e)
- {
- //MessageBox.Show("OnExit");
- base.OnExit(e);
- }
- }
- }
- <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
- <Style x:Key="TextBlock_yellow" TargetType="TextBlock">
- <Setter Property="Background" Value="Yellow"/>
- <Setter Property="VerticalAlignment" Value="Top"/>
- <Setter Property="HorizontalAlignment" Value="Left"/>
- <Setter Property="Width" Value="500"/>
- <Setter Property="Height" Value="100"/>
- <Setter Property="Margin" Value="5,10"/>
- <Setter Property="TextWrapping" Value="Wrap" />
- </Style>
- <Style x:Key="TextBox_yellow" TargetType="TextBox">
- <Setter Property="Background" Value="Yellow"/>
- <Setter Property="HorizontalAlignment" Value="Left"/>
- <Setter Property="VerticalAlignment" Value="Top"/>
- <Setter Property="Width" Value="500"/>
- <Setter Property="Height" Value="100"/>
- <Setter Property="Margin" Value="5,10"/>
- <Setter Property="AcceptsReturn" Value="True"/>
- <Setter Property="TextWrapping" Value="Wrap"/>
- </Style>
- </ResourceDictionary>
- <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:WpfApp_Hello"
- xmlns:system="clr-namespace:System;assembly=mscorlib">
- <system:String x:Key="LocalizeMessage_Chen">en-USA</system:String>
- <ControlTemplate x:Key="btnCustom" TargetType="Button">
- <Border Name="border" Background="Green"
- BorderThickness="2" BorderBrush="LightPink">
- <Grid x:Name="MyGrid">
- <Ellipse x:Name="MyEllipse"
- Fill="{TemplateBinding Background}"
- Stroke="{TemplateBinding Foreground}"/>
- <ContentPresenter HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>
- </Border>
- <ControlTemplate.Triggers>
- <Trigger Property="IsPressed" Value="True">
- <Setter TargetName="border" Property="Background" Value="Yellow"/>
- <Setter TargetName="border" Property="BorderBrush" Value="Black"/>
- </Trigger>
- <Trigger Property="IsMouseOver" Value="True" SourceName="MyGrid">
- <Setter TargetName="MyEllipse" Property="Stroke" Value="Red"/>
- <Setter TargetName="MyEllipse" Property="Fill" Value="Brown"/>
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- <ControlTemplate x:Key="btnCustom_StoryBoard" TargetType="{x:Type Button}">
- <Border Name="border" Background="Green">
- <Grid x:Name="MyGrid">
- <Ellipse x:Name="MyEllipse"
- Fill="{TemplateBinding Background}"
- Stroke="{TemplateBinding Foreground}"/>
- <ContentPresenter HorizontalAlignment="Left"
- VerticalAlignment="Top"/>
- </Grid>
- </Border>
- <ControlTemplate.Triggers>
- <Trigger Property="IsPressed" Value="True">
- <Setter TargetName="border" Property="Background" Value="Yellow"/>
- </Trigger>
- <Trigger Property="IsMouseOver" Value="True" SourceName="MyGrid">
- <Setter TargetName="MyEllipse" Property="Stroke" Value="Red"/>
- <Trigger.EnterActions>
- <BeginStoryboard>
- <Storyboard>
- <ColorAnimation Storyboard.TargetName="MyEllipse"
- Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
- To="Brown" Duration="0:0:1"/>
- </Storyboard>
- </BeginStoryboard>
- </Trigger.EnterActions>
- <Trigger.ExitActions>
- <BeginStoryboard>
- <Storyboard>
- <ColorAnimation Storyboard.TargetName="MyEllipse"
- Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
- To="{x:Null}" Duration="0:0:0.1">
- </ColorAnimation>
- </Storyboard>
- </BeginStoryboard>
- </Trigger.ExitActions>
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- <Style x:Key="Custom_Button_Chen_XXX" TargetType="Button">
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="Button">
- <Grid x:Name="Grid_Chen">
- <Border x:Name="bord_Chen"
- Background="{TemplateBinding Background}"
- BorderBrush="{TemplateBinding BorderBrush}"
- BorderThickness="{TemplateBinding BorderThickness}">
- </Border>
- <ContentPresenter HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>
- <ControlTemplate.Triggers>
- <Trigger Property="IsMouseOver" Value="True" SourceName="Grid_Chen">
- <Setter TargetName="bord_Chen" Property="BorderBrush" Value="Red"/>
- <Setter TargetName="bord_Chen" Property="BorderThickness" Value="8"/>
- <Setter TargetName="bord_Chen" Property="Background" Value="Yellow"/>
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </ResourceDictionary>
- <Window x:Class="WpfApp_Hello.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:WpfApp_Hello"
- xmlns:system="clr-namespace:System;assembly=mscorlib"
- mc:Ignorable="d"
- xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
- WindowStyle="ThreeDBorderWindow"
- ResizeMode="CanResizeWithGrip"
- MinWidth="600" Height="600" Width="1024"
- Title="MainWindow">
- <Window.DataContext>
- <Binding Source="{x:Static local:MainWindow.My_ViewModel}"/>
- </Window.DataContext>
- <Window.CommandBindings>
- <CommandBinding Command="{x:Static local:MainWindow.InkCanVas_Command}"
- CanExecute="InkCanVas_CanExecute"
- Executed="InkCanVas_Executed"/>
- <CommandBinding Command="ApplicationCommands.Close"
- Executed="Close_Executed"/>
- </Window.CommandBindings>
- <DockPanel x:Name="DockPanel_main">
- <Menu Height="22" x:Name="MyMenu" DockPanel.Dock="Top">
- <MenuItem Header="Common Commamds">
- <MenuItem Header="Paste" Command="ApplicationCommands.Paste"/>
- <MenuItem Header="Copy" Command="ApplicationCommands.Copy"/>
- <MenuItem Header="Open" Command="ApplicationCommands.Open"/>
- <Separator/>
- <MenuItem Header="Close" Command="ApplicationCommands.Close"/>
- </MenuItem>
- <MenuItem Header="Custom Commands" x:Name="MyMenuCmd">
- <MenuItem Header="InkCanVas" Command="{x:Static local:MainWindow.InkCanVas_Command}"/>
- <Separator/>
- </MenuItem>
- </Menu>
- <TextBox x:Name="TextBox_Chen" Text="TextBox_Chen"
- TextWrapping="Wrap" AcceptsReturn="True" >
- <TextBox.InputBindings>
- <KeyBinding Command="{Binding TextBox_KeyCommand_C_F1}"
- CommandParameter="{Binding ElementName=TextBox_Chen}"
- Modifiers="Ctrl" Key="F1"/>
- <MouseBinding Command="{Binding TextBox_MouseCommand_DoubleClick}"
- CommandParameter="{Binding ElementName=TextBox_Chen}"
- MouseAction="LeftDoubleClick" />
- </TextBox.InputBindings>
- </TextBox>
- </DockPanel>
- </Window>
- using System.ComponentModel;
- using System.Data;
- using System.Globalization;
- using System.IO;
- using System.IO.IsolatedStorage;
- using System.Reflection;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Xml.Serialization;
- namespace WpfApp_Hello
- {
- public abstract class MyViewModelBase : UIElement, INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler? PropertyChanged;
- public void OnPropertyChanged(string myPropertyName)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(myPropertyName));
- }
- public class RelayCommand : ICommand
- {
- public event EventHandler? CanExecuteChanged
- {
- add => CommandManager.RequerySuggested += value;
- remove => CommandManager.RequerySuggested -= value;
- }
- public RelayCommand(Action<object?> execute) : this(execute, null) { }
- public RelayCommand(Action<object?> execute, Predicate<object?>? canExecute)
- {
- ArgumentNullException.ThrowIfNull(execute, "RelayCommand throw exception__CHen");
- _execute = execute; _canExecute = canExecute;
- }
- private readonly Action<object?> _execute;
- private readonly Predicate<object?>? _canExecute;
- public bool CanExecute(object? parameter)
- {
- return _canExecute is null || _canExecute(parameter);
- }
- public void Execute(object? parameter)
- {
- _execute(parameter);
- }
- }
- }
- public partial class MyViewModel : MyViewModelBase
- {
- public static readonly StringBuilder Trace = new();
- public MyViewModel()
- {
- MyViewModel.Trace.AppendLine("public MyViewModel() ");
- }
- public MyViewModel(String str, Int32 In_int32)
- {
- MyViewModel.Trace.AppendLine($"public MyViewModel({str}, {In_int32})");
- }
- public static String About_WPF_feature()
- {
- StringBuilder WPF_feature = new("About WPF feature\n**************\n");
- try
- {
- System.Reflection.Assembly? assembly =
- typeof(MainWindow).Assembly ?? throw new Exception("assembly is null");
- //Assembly.GetEntryAssembly() ?? throw new Exception("assembly is null");
- string MainAssembly = $"{assembly.GetFiles()[0].Name}";
- WPF_feature.AppendLine(MainAssembly);
- String? XmalResource = System.Windows.Application.Current.TryFindResource(
- "LocalizeMessage_Chen") as String;
- WPF_feature.AppendLine("XmalResource LocalizeMessage_Chen=" + XmalResource);
- String query = "%AppData%"; //// "%SystemDrive%";
- String result = Environment.ExpandEnvironmentVariables(query);
- WPF_feature.AppendLine($"Result of query {query} = {result}");
- Type type = typeof(TextBox);
- PropertyMetadata MetaData = TextBox.TextProperty.GetMetadata(type);
- if (MetaData is FrameworkPropertyMetadata f)
- {
- WPF_feature.AppendLine($"{type.Name} DefaultUpdateSourceTrigger= {f?.DefaultUpdateSourceTrigger}");
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error:" + ex.Message);
- }
- finally
- {
- WPF_feature.AppendLine("*****************");
- }
- return WPF_feature.ToString();
- }
- private RelayCommand? _TextBox_MouseCommand_DoubleClick = null;
- public ICommand TextBox_MouseCommand_DoubleClick
- {
- get
- {
- _TextBox_MouseCommand_DoubleClick ??= new RelayCommand(
- Execute_TextBox_MouseCommand_DoubleClick);
- return _TextBox_MouseCommand_DoubleClick;
- }
- }
- private RelayCommand? _TextBox_KeyCommand_C_F1 = null;
- public ICommand TextBox_KeyCommand_C_F1
- {
- get
- {
- _TextBox_KeyCommand_C_F1 ??= new RelayCommand(
- Execute_TextBox_KeyCommand_C_F1,
- CanExecute_TextBox_KeyCommand_C_F1);
- return _TextBox_KeyCommand_C_F1;
- }
- }
- private void Execute_TextBox_KeyCommand_C_F1(object? parameter)
- {
- if (parameter is TextBox MyTextBox)
- {
- MyTextBox.Foreground = new SolidColorBrush(SystemColors.AccentColor);
- MessageBox.Show($"Text.Length= {MyTextBox.Text.Length}");
- }
- }
- private bool CanExecute_TextBox_KeyCommand_C_F1(object? parameter)
- {
- return true;
- }
- private void Execute_TextBox_MouseCommand_DoubleClick(object? parameter)
- {
- if (parameter is TextBox MyTextBox)
- {
- MainWindow.AddText_And_MoveCursorToEnd(MyTextBox,
- "***\n" + MyViewModel.Trace.ToString());
- MyViewModel.Trace.Clear();
- }
- }
- }
- public partial class MainWindow : Window
- {
- public static MainWindow Singleton { get; set; }
- static Action<MainWindow>? MyInitialActions = null;
- class AddInitializationAction
- {
- public AddInitializationAction(Action<MainWindow> x)
- {
- MainWindow.MyInitialActions += x;
- }
- }
- public MainWindow()
- {
- InitializeComponent();
- if (Singleton != null) throw new Exception("Singleton");
- Singleton = this;
- MyInitialWindowState.Begin(this);
- MyInitialActions?.Invoke(this);
- AddText_And_MoveCursorToEnd(TextBox_Chen,
- MyViewModel.About_WPF_feature() + MyViewModel.Trace.ToString());
- MyViewModel.Trace.Clear();
- }
- static public void AddText_And_MoveCursorToEnd(TextBox txtbox, String text)
- {
- txtbox.Text += "\n" + text;
- txtbox.CaretIndex = txtbox.Text.Length;
- txtbox.Focus();
- txtbox.ScrollToEnd();
- }
- static private MyViewModel my_viewModel = new MyViewModel();
- static public MyViewModel My_ViewModel
- {
- get => my_viewModel;
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- MyInitialWindowState.SaveInitialData(this);
- base.OnClosing(e);
- }
- public void Close_Executed(object sender, RoutedEventArgs e)
- {
- this.Close();//Application.Current.Shutdown();
- }
- }
- public class MyApp_Data
- {
- public Rect rect;
- public WindowState windowState;
- }
- public class MyInitialWindowState
- {
- public static readonly IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetMachineStoreForAssembly();
- public const string filenameIso = "MyIsolatedStorageFileName.iso";
- static public void Begin(MainWindow x)
- {
- MyViewModel.Trace.AppendLine("Begin ===> isolatedStorageFile.GetFileNames ======");
- foreach (String file in isolatedStorageFile.GetFileNames())
- {
- MyViewModel.Trace.AppendLine(file);
- }
- MyViewModel.Trace.AppendLine("End ===> isolatedStorageFile.GetFileNames ======");
- if (isolatedStorageFile.FileExists(filenameIso))
- try
- {
- using var isolatedStorageFileStream =
- new IsolatedStorageFileStream(filenameIso,
- FileMode.Open, isolatedStorageFile);
- var xmlSerializer = new XmlSerializer(typeof(MyApp_Data));
- MyApp_Data? MyAppData =
- xmlSerializer.Deserialize(isolatedStorageFileStream) as MyApp_Data;
- if (MyAppData is not null)
- {
- x.Left = MyAppData.rect.Left;
- x.Top = MyAppData.rect.Top;
- x.Width = MyAppData.rect.Width;
- x.Height = MyAppData.rect.Height;
- x.WindowState = MyAppData.windowState == WindowState.Minimized ?
- WindowState.Normal : MyAppData.windowState;
- //#if TRACE_Chen
- var sw = new StringWriter();
- xmlSerializer.Serialize(sw, MyAppData);
- MyViewModel.Trace.AppendLine(sw.ToString());
- //#endif
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message + " " + filenameIso);
- }
- }
- static public void SaveInitialData(MainWindow x)
- {
- MyApp_Data MyAppData = new()
- {
- rect = x.RestoreBounds,
- windowState = x.WindowState
- };
- try
- {
- using var isolatedStorageFileStream =
- new IsolatedStorageFileStream(filenameIso,
- FileMode.Create, isolatedStorageFile);
- var xmlSerializer = new XmlSerializer(MyAppData.GetType());
- xmlSerializer.Serialize(isolatedStorageFileStream, MyAppData);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message + " " + filenameIso);
- }
- }
- }
- [ValueConversion(typeof(string), typeof(Brush))]
- public class MyStringToBrushConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- BrushConverter brushConverter = new();
- object? MyObj = brushConverter.ConvertFromString((string)value);
- if (MyObj is null) throw new NoNullAllowedException("MyStringToBrushConverter");
- string? MyBrush = brushConverter.ConvertToInvariantString(MyObj);
- //MessageBox.Show(MyBrush);
- return MyObj;
- }
- public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException("MyStringToBrushConverter ConvertBack");
- }
- }
- [ValueConversion(typeof(string), typeof(DateTime))]
- public class MyClockConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value is DateTime) return String.Format((string)parameter, value);
- throw new Exception("Error in MyClockConverter.Convert");
- }
- public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException("MyClockConverter");
- }
- }
- public class MyMultiValueConverter : IMultiValueConverter
- {
- public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
- {
- return values.Clone();
- }
- public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException("MyMultiValueConverter");
- }
- }
- public class MyFormattedMultiTextConverter : IMultiValueConverter
- {
- public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
- {
- return String.Format((String)parameter, values);
- }
- public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
- }
- <Window x:Class="WpfApp_Hello.Window_Ink"
- 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:WpfApp_Hello"
- mc:Ignorable="d"
- Title="Window_Ink" Height="486" Width="800" >
- <StackPanel>
- <ScrollViewer HorizontalScrollBarVisibility="Visible" >
- <InkCanvas Name="inkCanvas" Background="LemonChiffon" Width="3333" Height="333">
- <InkCanvas.DefaultDrawingAttributes>
- <DrawingAttributes/>
- </InkCanvas.DefaultDrawingAttributes>
- <Line Stroke="Red" X1="0" Y1="0" X2="333" Y2="333" Height="333" Width="681"/>
- <Line Stroke="Green" X1="3" Y1="333" X2="333" Y2="3"/>
- <Ellipse Stroke="Yellow" Width="33" Height="44" Fill="Green" Margin="123,123"/>
- </InkCanvas>
- </ScrollViewer>
- <DockPanel LastChildFill="False" Height="20">
- <RadioButton Content=" " Checked="RadioButton_Checked" Background="Red"/>
- <RadioButton Content=" " Checked="RadioButton_Checked" Background="Green"/>
- <RadioButton Content=" " Checked="RadioButton_Checked" Background="Blue"/>
- <RadioButton Content="DefaultColor" Checked="RadioButton_Checked_4"/>
- </DockPanel>
- <UniformGrid Columns="3">
- <Button Content="Open file" Width="80" Click="Button_Click_Open"/>
- <Button Content="Save file" Width="160" Click="Button_Click_Save"/>
- </UniformGrid>
- </StackPanel>
- </Window>
- using Microsoft.Win32;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Markup;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Shapes;
- using System.Xml;
- using System.Xml.Serialization;
- namespace WpfApp_Hello
- {
- /// <summary>
- /// Interaction logic for Window_Ink.xaml
- /// </summary>
- public partial class Window_Ink : Window
- {
- public Window_Ink()
- {
- InitializeComponent();
- defaultDrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone();
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- MainWindow aa = (MainWindow)this.Owner;
- aa.BOOL_CanExecuted_Ink = true;
- aa.Activate();
- base.OnClosing(e);
- }
- private void RadioButton_Checked(object sender, RoutedEventArgs e)
- {
- inkCanvas.DefaultDrawingAttributes.Color =
- (System.Windows.Media.Color)ColorConverter.ConvertFromString(
- ((RadioButton)e.Source).Background.ToString());
- }
- private readonly DrawingAttributes defaultDrawingAttributes;
- private void RadioButton_Checked_4(object sender, RoutedEventArgs e)
- {
- inkCanvas.DefaultDrawingAttributes.Color = defaultDrawingAttributes.Color;
- }
- private void Button_Click_Open(object sender, RoutedEventArgs e)
- {
- var openFileDialog = new OpenFileDialog()
- {
- CheckFileExists = true,
- Filter =
- "Ink serialize fmt(*.isf)|*.isf|XAML(*.Xaml)|*.Xaml| All file (*.*)|*.*"
- };
- if (openFileDialog.ShowDialog(this) == true)
- try
- {
- if (openFileDialog.FilterIndex == 1)
- inkCanvas.Strokes = new System.Windows.Ink.StrokeCollection(
- openFileDialog.OpenFile());
- else if (openFileDialog.FilterIndex == 2)
- {
- XmlReader xmlReader = XmlReader.Create(openFileDialog.OpenFile());
- inkCanvas.Strokes = XamlReader.Load(xmlReader) as StrokeCollection;
- }
- else throw new Exception(
- $"error:openFileDialog.FilterIndex={openFileDialog.FilterIndex}");
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void Button_Click_Save(object sender, RoutedEventArgs e)
- {
- var saveFileDialog = new SaveFileDialog
- {
- OverwritePrompt = true,
- Filter =
- "Ink serialize fmt(*.isf)|*.isf|XAML(*.Xaml)|*.Xaml| All file (*.*)|*.*"
- };
- if (saveFileDialog.ShowDialog(this) == true)
- try
- {
- if (saveFileDialog.FilterIndex == 1)
- inkCanvas.Strokes.Save(saveFileDialog.OpenFile());
- else if (saveFileDialog.FilterIndex == 2)
- XamlWriter.Save(inkCanvas.Strokes, saveFileDialog.OpenFile());
- else throw new Exception(
- $"error:saveFileDialog.FilterIndex={saveFileDialog.FilterIndex}");
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
- public partial class MainWindow
- {
- static private RoutedCommand? _InkCanVas_Command = null;
- static public RoutedCommand InkCanVas_Command
- {
- get
- {
- if (_InkCanVas_Command == null)
- {
- _InkCanVas_Command = new RoutedCommand();
- }
- return _InkCanVas_Command;
- }
- }
- public bool BOOL_CanExecuted_Ink = true;
- public void InkCanVas_CanExecute(object sender, CanExecuteRoutedEventArgs e)
- {
- e.CanExecute = BOOL_CanExecuted_Ink;
- }
- public void InkCanVas_Executed(object sender, RoutedEventArgs e)
- {
- Window_Ink w4 = new Window_Ink() { Owner = this };
- w4.Show();
- BOOL_CanExecuted_Ink = false;
- }
- }
- }
- <Window x:Class="WpfApp_Hello.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:WpfApp_Hello"
- mc:Ignorable="d"
- xmlns:system="clr-namespace:System;assembly=mscorlib"
- WindowStyle="ThreeDBorderWindow"
- ResizeMode="CanResizeWithGrip"
- WindowStartupLocation="CenterOwner"
- SizeToContent="Height"
- Title="Window1" Height="600" Width="800">
- <Window.Resources>
- <local:MyFormattedMultiTextConverter x:Key="MyFormattedMultiTextConverterKey"/>
- <local:MyClockConverter x:Key="MyClockConverterKey"/>
- <!-- <Style TargetType="Button"> -->
- <Style TargetType="{x:Type Button}">
- <Setter Property="Background" Value="#4E1A3D"/>
- <Setter Property="Foreground" Value="White"/>
- <Setter Property="BorderThickness" Value="5"/>
- <Setter Property="BorderBrush">
- <Setter.Value>
- <LinearGradientBrush>
- <GradientStop Offset="0.0" Color="#4A1A3D"/>
- <GradientStop Offset="1.0" Color="Salmon"/>
- </LinearGradientBrush>
- </Setter.Value>
- </Setter>
- </Style>
- </Window.Resources>
- <Window.DataContext>
- <Binding Source="{x:Static local:MainWindow.My_ViewModel}"/>
- </Window.DataContext>
- <StackPanel x:Name="MyStackPanel_w1">
- <Label x:Name="MyLabel2" Height="23">
- <Label.Content>
- <Binding Path="DateTime_Now"
- Converter="{StaticResource MyClockConverterKey}"
- ConverterParameter=" {0:yyyy-MM-dd hh:mm:ss} " />
- </Label.Content>
- </Label>
- <TextBlock x:Name="MyTextBlock1"
- Background="{DynamicResource {x:Static SystemColors.AccentColorLight3BrushKey}}"
- Foreground="{DynamicResource {x:Static SystemColors.AccentColorDark1BrushKey}}"
- FontSize="14" FontFamily="Times New Roman"
- Height="25" >
- <TextBlock.Text>
- <MultiBinding Converter="{StaticResource MyFormattedMultiTextConverterKey}"
- ConverterParameter=".Net Version:{0} Now:{1}">
- <Binding Source="{x:Static system:Environment.Version}" />
- <Binding Path="DateTime_Now"
- Converter="{StaticResource MyClockConverterKey}"
- ConverterParameter=" {0:yyyy-MM-dd hh:mm:ss} "/>
- </MultiBinding>
- </TextBlock.Text>
- </TextBlock>
- <ScrollViewer HorizontalScrollBarVisibility="Auto"
- VerticalScrollBarVisibility="Auto"
- Height="450">
- <TextBlock x:Name="MyTextBlock" Background="LightYellow" >
- <TextBlock.Text>
- <MultiBinding Converter="{StaticResource MyFormattedMultiTextConverterKey}"
- ConverterParameter="{}{0}
- SystemDirectory:{1}
- UserName:{2}
- Today:{3:d MMM,yyyy}
- {4}
- " >
- <Binding Path="DateTime_Now_Ticks" />
- <Binding Source="{x:Static system:Environment.SystemDirectory}" />
- <Binding Source="{x:Static system:Environment.UserName}" />
- <Binding Source="{x:Static system:DateTime.Today}" />
- <Binding Source="{x:Static local:CodeFromXaml.Resource1String}"/>
- </MultiBinding>
- </TextBlock.Text>
- <TextBlock.ContextMenu>
- <ContextMenu MenuItem.Click="ContextMenu_Click">
- <HeaderedContentControl Header="Red" Foreground="Red"/>
- <HeaderedContentControl Header="Green" Foreground="Green"/>
- <HeaderedContentControl Header="Orange" Foreground="Orange"/>
- </ContextMenu>
- </TextBlock.ContextMenu>
- </TextBlock>
- </ScrollViewer>
- <!--
- <x:Code>
- <![CDATA[
- private void RadioButton2_Checked_inline(object sender, RoutedEventArgs e)
- {
- }
- ]]>
- </x:Code>
- -->
- </StackPanel>
- </Window>
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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;
- using System.Windows.Threading;
- namespace WpfApp_Hello
- {
- public partial class MainWindow
- {
- AddInitializationAction WW1 =
- new(Window1.my_menu.MyInitialActions);
- }
- public partial class Window1 : Window, ICreateWindow
- {
- public static Add_Menu_Item<Window1> my_menu = new("Window1");
- void ICreateWindow.MyShow()
- {
- Owner = my_menu.OwnerWindow;
- Show();
- my_menu.CanExecuted = false;
- }
- public Window1()
- {
- InitializeComponent();
- MyInitialization();
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- my_menu.CanExecuted = true;
- base.OnClosing(e);
- }
- Style? buttonStyle0;
- Style? buttonStyle1;
- bool buttonStyleSwitch = false;
- void MyInitialization()
- {
- var btn = new Button
- {
- Content = Btn_Content1
- };
- btn.Click += Button_Click;
- buttonStyle0 = btn.Style;
- MyStackPanel_w1.Children.Add(btn);
- buttonStyle1 = btn.Style;
- (new DispatcherTimer(
- TimeSpan.FromSeconds(1),
- DispatcherPriority.Normal,
- TimerOnTick,
- Dispatcher.CurrentDispatcher)
- ).Start();
- }
- void TimerOnTick(object? sender, EventArgs e)
- {
- MainWindow.My_ViewModel.DateTime_Now = DateTime.Now;
- }
- const string Btn_Content0 = "Orignal Buttton style";
- const string Btn_Content1 = "implicit key in resource";
- void Button_Click(object sender, RoutedEventArgs e)
- {
- Button btn = (Button)sender;
- buttonStyleSwitch = !buttonStyleSwitch;
- btn.Content = buttonStyleSwitch ? Btn_Content0 : Btn_Content1;
- btn.Style = buttonStyleSwitch ? buttonStyle0 : buttonStyle1;
- MainWindow.My_ViewModel.DateTime_Now_Ticks = $"--- {DateTime.Now.Ticks} ----";
- }
- void ContextMenu_Click(object sender, RoutedEventArgs e)
- {
- MenuItem? menuItem = e.OriginalSource as MenuItem;
- HeaderedContentControl? headeredContentControl = menuItem?.Header as HeaderedContentControl;
- if (headeredContentControl?.Header is String str)
- {
- System.Windows.Media.Color color = (System.Windows.Media.Color)
- System.Windows.Media.ColorConverter.ConvertFromString(str);
- MyTextBlock.Foreground = new SolidColorBrush(color);
- }
- }
- }
- public interface ICreateWindow
- {
- void MyShow();
- }
- public class Add_Menu_Item<WIN> where WIN : ICreateWindow, new()
- {
- String MyHeader;
- bool BOOL_CanExecuted = true;
- public bool CanExecuted
- {
- get => BOOL_CanExecuted;
- set => BOOL_CanExecuted = value;
- }
- public Add_Menu_Item(String Header)
- {
- MyHeader = Header;
- }
- public Window? OwnerWindow;
- public void MyInitialActions(MainWindow mainWindow)
- {
- OwnerWindow = mainWindow;
- var Routed_Command = new RoutedCommand();
- mainWindow.MyMenuCmd.Items.Add(
- new MenuItem()
- {
- Header = MyHeader,
- Command = Routed_Command
- }
- );
- mainWindow.CommandBindings.Add(
- new CommandBinding
- (
- Routed_Command,
- CreateWindow_Executed,
- CreateWindow_CanExecute
- )
- );
- }
- void CreateWindow_CanExecute(object sender, CanExecuteRoutedEventArgs e)
- {
- e.CanExecute = CanExecuted;
- }
- void CreateWindow_Executed(object sender, RoutedEventArgs e)
- {
- (new WIN()).MyShow();
- }
- }
- public partial class MyViewModel
- {
- public DateTime DateTime_Now
- {
- get { return (DateTime)GetValue(DateTime_NowProperty); }
- set { SetValue(DateTime_NowProperty, value); }
- }
- public event RoutedPropertyChangedEventHandler<DateTime> DateTimeChanged
- {
- add { AddHandler(DateTimeChangedEvent, value); }
- remove { RemoveHandler(DateTimeChangedEvent, value); }
- }
- static readonly DependencyProperty DateTime_NowProperty =
- DependencyProperty.Register(
- nameof(DateTime_Now), typeof(DateTime), typeof(MyViewModel),
- new FrameworkPropertyMetadata(DateTime.Now,
- new PropertyChangedCallback(OnDateTimeChangedCallback))
- );
- static readonly RoutedEvent DateTimeChangedEvent =
- EventManager.RegisterRoutedEvent(
- nameof(DateTimeChanged), RoutingStrategy.Bubble,
- typeof(RoutedPropertyChangedEventHandler<DateTime>),
- typeof(MyViewModel)
- );
- static void OnDateTimeChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
- {
- var DateTimeObj = (MyViewModel)obj;
- var e = new RoutedPropertyChangedEventArgs<DateTime>(
- (DateTime)args.OldValue, (DateTime)args.NewValue,
- DateTimeChangedEvent
- );
- DateTimeObj.OnDateTimeChanged(e);
- }
- protected virtual void OnDateTimeChanged(RoutedPropertyChangedEventArgs<DateTime> args)
- {
- RaiseEvent(args);
- }
- String _DateTime_Now_Ticks = "My type name is " +
- nameof(MainWindow.My_ViewModel.DateTime_Now_Ticks);
- public String DateTime_Now_Ticks
- {
- get => _DateTime_Now_Ticks;
- set
- {
- _DateTime_Now_Ticks = value;
- OnPropertyChanged(nameof(DateTime_Now_Ticks));
- }
- }
- }
- public partial class CodeFromXaml
- {
- public static String Resource1String
- {
- get =>
- @"
- public partial class App : System.Windows.Application {
- private bool _contentLoaded;
- /// <summary>
- /// InitializeComponent
- /// </summary>
- [System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [System.CodeDom.Compiler.GeneratedCodeAttribute(""PresentationBuildTasks"", ""9.0.8.0"")]
- public void InitializeComponent() {
- if (_contentLoaded) {
- return;
- }
- _contentLoaded = true;
- #line 5 ""..\..\..\..\App.xaml""
- this.StartupUri = new System.Uri(""MainWindow.xaml"", System.UriKind.Relative);
- #line default
- #line hidden
- System.Uri resourceLocater = new System.Uri(""/WpfApp_Hello;component/app.xaml"", System.UriKind.Relative);
- #line 1 ""..\..\..\..\App.xaml""
- System.Windows.Application.LoadComponent(this, resourceLocater);
- #line default
- #line hidden
- }
- /// <summary>
- /// Application Entry Point.
- /// </summary>
- [System.STAThreadAttribute()]
- [System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [System.CodeDom.Compiler.GeneratedCodeAttribute(""PresentationBuildTasks"", ""9.0.8.0"")]
- public static void Main() {
- WpfApp_Hello.App app = new WpfApp_Hello.App();
- app.InitializeComponent();
- app.Run();
- }
- }
- ";
- }
- }
- }
- <Window x:Class="WpfApp_Hello.Window2"
- 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:WpfApp_Hello"
- mc:Ignorable="d"
- Title="Window2">
- <Window.Resources>
- <local:MyMultiValueConverter x:Key="MyMultiValueConverterKey"/>
- </Window.Resources>
- <Window.DataContext>
- <Binding Source="{x:Static local:MainWindow.My_ViewModel}"/>
- </Window.DataContext>
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- </Grid.ColumnDefinitions>
- <StackPanel Grid.Column="0">
- <TextBlock Style="{StaticResource TextBlock_yellow}">
- <TextBlock.Text>
- <Binding Path="Text_MVVM_PropertyChanged"/>
- </TextBlock.Text>
- </TextBlock>
- <TextBlock Text="{Binding Path=Text_MVVM1_Explicit}"
- Style="{StaticResource TextBlock_yellow}" />
- <TextBlock Text="{Binding Path=Text_MVVM2_Explicit}"
- Style="{StaticResource TextBlock_yellow}" />
- </StackPanel>
- <StackPanel Grid.Column="1">
- <TextBox Style="{StaticResource TextBox_yellow}"
- Text="{Binding Path=Text_MVVM_PropertyChanged,
- UpdateSourceTrigger=PropertyChanged}"
- />
- <TextBox x:Name="MyTextBox_1"
- Style="{StaticResource TextBox_yellow}"
- Text="{Binding Path=Text_MVVM1_Explicit,
- UpdateSourceTrigger=Explicit}"
- TextChanged="MyTextBox_1_TextChanged"
- />
- <TextBox x:Name="MyTextBox_2"
- Style="{StaticResource TextBox_yellow}"
- TextChanged="MyTextBox_2_TextChanged"
- >
- <TextBox.Text>
- <Binding Path="Text_MVVM2_Explicit"
- UpdateSourceTrigger="Explicit"/>
- </TextBox.Text>
- </TextBox>
- <Button x:Name="ExplicitButton" Content="Explicit"
- Command="{Binding Command_ExplicitButton}"
- Background="Yellow" IsEnabled="False"
- Margin="100,10" Height="40" Width="150">
- <Button.CommandParameter>
- <MultiBinding Converter="{StaticResource MyMultiValueConverterKey}">
- <Binding ElementName="ExplicitButton"/>
- <Binding ElementName="MyTextBox_1"/>
- <Binding ElementName="MyTextBox_2"/>
- </MultiBinding>
- </Button.CommandParameter>
- </Button>
- </StackPanel>
- </Grid>
- </Window>
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfApp_Hello
- {
- public partial class MainWindow
- {
- AddInitializationAction WW2 =
- new(Window2.my_menu.MyInitialActions);
- }
- public partial class Window2 : Window, ICreateWindow
- {
- public static Add_Menu_Item<Window2> my_menu = new("Window2");
- void ICreateWindow.MyShow()
- {
- Owner = my_menu.OwnerWindow;
- Show();
- my_menu.CanExecuted = false;
- }
- public Window2()
- {
- InitializeComponent();
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- my_menu.CanExecuted = true;
- base.OnClosing(e);
- }
- private void MyTextBox_1_TextChanged(object sender, TextChangedEventArgs e)
- {
- if (ExplicitButton is not null)
- ExplicitButton.IsEnabled = true;
- }
- private void MyTextBox_2_TextChanged(object sender, TextChangedEventArgs e)
- {
- if (ExplicitButton is not null)
- ExplicitButton.IsEnabled = true;
- }
- }
- public partial class MyViewModel : MyViewModelBase
- {
- RelayCommand? _Command_ExplicitButton = null;
- public ICommand Command_ExplicitButton
- {
- get
- {
- _Command_ExplicitButton ??=
- new RelayCommand(Execute_ExplicitButton);
- return _Command_ExplicitButton;
- }
- }
- private void Execute_ExplicitButton(object? parameter)
- {
- object[]? objects = parameter as object[];
- Button? Explicit_Button = objects?[0] as Button;
- TextBox? MyTextBox_1 = objects?[1] as TextBox;
- TextBox? MyTextBox_2 = objects?[2] as TextBox;
- MyTextBox_1?.GetBindingExpression(TextBox.TextProperty).
- UpdateSource();
- {
- BindingExpression? bindingExpression_2 =
- MyTextBox_2?.GetBindingExpression(TextBox.TextProperty);
- bindingExpression_2?.UpdateSource();
- }
- if (Explicit_Button is not null) Explicit_Button.IsEnabled = false;
- }
- private String _Text_MVVM_PropertyChanged = "PropertyChanged >>";
- private String _Text_MVVM1_Explicit = "Explicit 1>>";
- private String _Text_MVVM2_Explicit = "Explicit 2>>";
- public String Text_MVVM_PropertyChanged
- {
- get => _Text_MVVM_PropertyChanged;
- set
- {
- _Text_MVVM_PropertyChanged = value;
- OnPropertyChanged(nameof(Text_MVVM_PropertyChanged));
- }
- }
- public String Text_MVVM1_Explicit
- {
- get => _Text_MVVM1_Explicit;
- set
- {
- _Text_MVVM1_Explicit = value;
- OnPropertyChanged(nameof(Text_MVVM1_Explicit));
- }
- }
- public String Text_MVVM2_Explicit
- {
- get => _Text_MVVM2_Explicit;
- set
- {
- _Text_MVVM2_Explicit = value;
- OnPropertyChanged(nameof(Text_MVVM2_Explicit));
- }
- }
- }
- }
- <Window x:Class="WpfApp_Hello.Window3"
- 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:MySystem="clr-namespace:System;assembly=mscorlib"
- xmlns:local="clr-namespace:WpfApp_Hello"
- mc:Ignorable="d"
- Title="Window3" Width="1024">
- <Window.DataContext>
- <Binding Source="{x:Static local:MainWindow.My_ViewModel}"/>
- </Window.DataContext>
- <StackPanel >
- <TextBlock Name="TextBlock_W3"
- Background="Bisque" Height="100" Margin="8"
- Text="{x:Static MySystem:Environment.MachineName}">
- </TextBlock>
- <TextBox x:Name="MyTextBox1" AcceptsReturn="True"
- TextWrapping="Wrap" Height="100" Margin="8">
- <TextBox.Text>
- <x:Static Member="MySystem:Environment.MachineName"/>
- </TextBox.Text>
- </TextBox>
- <Label
- Foreground="Green" Height="30" Width="300" Margin="8">
- <Label.BorderBrush>Yellow</Label.BorderBrush>
- <Label.BorderThickness>3</Label.BorderThickness>
- <Label.Background>
- <Binding Path="ColorName"
- Converter="{x:Static local:Window3.My_StringToBrushConverter}" />
- </Label.Background>
- <Label.Content>
- <x:Static Member="MySystem:Environment.SystemDirectory"/>
- </Label.Content>
- </Label>
- <Button Content="Test Binding" Click="Button_Click"
- Width="200" Height="41" Margin="8" >
- </Button>
- <Label Content ="{x:Static MySystem:Environment.SystemDirectory}"
- Foreground="Green" Height="30" Width="300" Margin="8"
- x:Name="MyLabel_3">
- <Label.BorderBrush>Yellow</Label.BorderBrush>
- <Label.BorderThickness>3</Label.BorderThickness>
- </Label>
- <Grid Margin="11,11">
- <Button Template="{StaticResource btnCustom}" Background="Gold"
- HorizontalAlignment="Left" Width="100" Height="50"
- Content="Custom button" Click="Button_Click"
- >
- <Button.ToolTip>
- <TextBlock> ToolTip</TextBlock>
- </Button.ToolTip>
- </Button>
- <Button Template="{StaticResource btnCustom_StoryBoard}" Foreground="Blue"
- HorizontalAlignment="Center" Width="200" Height="50"
- Content="Test StoryBoard"
- />
- <Button Style="{StaticResource Custom_Button_Chen}"
- HorizontalAlignment="Right" Width="200" Height="50"
- BorderBrush="HotPink"
- BorderThickness="5"
- Background="DarkGoldenrod"
- Content="Custom_Button_Chen OK" Click="Button_Click"
- />
- </Grid>
- </StackPanel>
- </Window>
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfApp_Hello
- {
- public partial class MainWindow
- {
- AddInitializationAction WW3 =
- new(Window3.my_menu.MyInitialActions);
- }
- public partial class Window3 : Window, ICreateWindow
- {
- public static Add_Menu_Item<Window3> my_menu = new("Window3");
- void ICreateWindow.MyShow()
- {
- Owner = my_menu.OwnerWindow;
- Show();
- my_menu.CanExecuted = false;
- }
- public Window3()
- {
- InitializeComponent();
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- my_menu.CanExecuted = true;
- base.OnClosing(e);
- }
- private static MyStringToBrushConverter _My_StringToBrushConverter = new();
- public static MyStringToBrushConverter My_StringToBrushConverter
- {
- get => _My_StringToBrushConverter;
- }
- private static MyViewModel _MyViewModelKey_XXX = new("Blue", 789);
- public static MyViewModel MyViewModelKey_XXX
- {
- get => _MyViewModelKey_XXX;
- }
- String[] MyCOLOR = ["Red", "Black", "YellowGreen"];
- UInt32 ColorIndex = 0;
- MyViewModel? MyViewModelObject = null;
- Binding? MyBinding1;
- Binding? MyBinding2;
- Binding? MyBinding3;
- BindingExpressionBase? bindingExpressionBase1;
- BindingExpressionBase? bindingExpressionBase2;
- BindingExpressionBase? bindingExpressionBase3;
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- if (MyViewModelObject == null)
- {
- MyViewModelObject = new();
- MyBinding1 = new(nameof(MyViewModel.ColorName))
- {
- Source = MyViewModelObject,
- Converter = new MyStringToBrushConverter()
- };
- bindingExpressionBase1 =
- MyLabel_3.SetBinding(Label.BackgroundProperty, MyBinding1);
- if (bindingExpressionBase1.HasError)
- MessageBox.Show("bindingExpressionBase1.ValidationError");
- //--------------------------------------------------
- MyBinding2 = new(nameof(MyViewModel.MyText3))
- {
- Source = MyViewModelObject,
- Mode = BindingMode.TwoWay,
- UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
- //UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
- };
- bindingExpressionBase2 =
- MyTextBox1.SetBinding(TextBox.TextProperty, MyBinding2);
- if (bindingExpressionBase2.HasError)
- MessageBox.Show("bindingExpressionBase2.ValidationError");
- //----------------------------------------------------
- MyBinding3 = new(nameof(MyViewModel.MyText3))
- {
- Source = MyViewModelObject
- };
- bindingExpressionBase3 = TextBlock_W3.SetBinding(TextBlock.TextProperty, MyBinding3);
- if (bindingExpressionBase3.HasError)
- MessageBox.Show("bindingExpressionBase2.ValidationError");
- }
- if (++ColorIndex >= MyCOLOR.Length) ColorIndex = 0;
- MainWindow.My_ViewModel.ColorName = MyCOLOR[ColorIndex];
- MyViewModelObject.ColorName = MyCOLOR[ColorIndex];
- MyViewModelObject.MyText3 = $"{DateTime.Now.Ticks} Tow way";
- }
- }
- public partial class MyViewModel : MyViewModelBase
- {
- private string _ColorName = "#FF800080";
- public String ColorName
- {
- get { return _ColorName; }
- set
- {
- _ColorName = value;
- OnPropertyChanged(nameof(ColorName));
- }
- }
- private String _MyText3 = string.Empty;
- public String MyText3
- {
- get => _MyText3;
- set
- {
- _MyText3 = value;
- OnPropertyChanged(nameof(MyText3));
- }
- }
- }
- }
- <Window x:Class="WpfApp_Hello.Window4"
- 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:WpfApp_Hello"
- xmlns:MyControls="clr-namespace:WpfControlLibrary_Hello;assembly=WpfControlLibrary_hello"
- mc:Ignorable="d"
- Title="Window4" Height="450" Width="800">
- <Grid>
- <MyControls:Get_UserControl Background="LightBlue"/>
- </Grid>
- </Window>
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfApp_Hello
- {
- public partial class MainWindow
- {
- AddInitializationAction WW4 =
- new(Window4.my_menu.MyInitialActions);
- }
- public partial class Window4 : Window, ICreateWindow
- {
- public static Add_Menu_Item<Window4> my_menu = new("UserControl");
- void ICreateWindow.MyShow()
- {
- Owner = my_menu.OwnerWindow;
- Show();
- my_menu.CanExecuted = false;
- }
- public Window4()
- {
- InitializeComponent();
- }
- protected override void OnClosing(CancelEventArgs e)
- {
- my_menu.CanExecuted = true;
- MainWindow aa = (MainWindow)this.Owner;
- aa.Activate();
- base.OnClosing(e);
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_Data_Validation"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- xmlns:system="clr-namespace:System;assembly=mscorlib"
- d:DesignHeight="450" d:DesignWidth="800">
- <UserControl.Resources>
- <Style TargetType="{x:Type TextBox}" x:Key="textBoxInError">
- <Setter Property="Validation.ErrorTemplate">
- <Setter.Value>
- <ControlTemplate>
- <DockPanel>
- <Border BorderBrush="OrangeRed" BorderThickness="4">
- <AdornedElementPlaceholder x:Name="MyAdorner"/>
- </Border>
- <Expander ExpandDirection="Right">
- <Grid>
- <Rectangle Stroke="Blue" Fill="PaleVioletRed"/>
- <TextBlock Text="{Binding
- ElementName=MyAdorner,
- Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}"
- />
- </Grid>
- </Expander>
- </DockPanel>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- <Style.Triggers>
- <Trigger Property="Validation.HasError" Value="true">
- <Setter
- Property="ToolTip"
- Value="{Binding
- RelativeSource={x:Static RelativeSource.Self},
- Path=(Validation.Errors)[0].ErrorContent}"/>
- <Setter Property="Background" Value="DarkSalmon"/>
- </Trigger>
- <Trigger Property="Validation.HasError" Value="false">
- <Setter Property="ToolTip" Value="OK"/>
- </Trigger>
- </Style.Triggers>
- </Style>
- </UserControl.Resources>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition/>
- <RowDefinition/>
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition/>
- <ColumnDefinition/>
- </Grid.ColumnDefinitions>
- <TextBox Style="{StaticResource textBoxInError}"
- Width="100" Height="30"
- BorderThickness="2" BorderBrush="SpringGreen"
- >
- <TextBox.Text>
- <Binding
- RelativeSource="{
- RelativeSource FindAncestor,
- AncestorType={x:Type local:UserControl_Data_Validation}}"
- Path="MySubClassObj.MyTestBindingRules"
- UpdateSourceTrigger="PropertyChanged"
- >
- <!--
- UpdateSourceExceptionFilter="{x:Static
- local:MyRangeRule.ExceptionFilterCallback}"
- ValidatesOnExceptions ="True"
- <ExceptionValidationRule/>
- -->
- <Binding.ValidationRules>
- <local:MyRangeRule Min="0" Max="1000" />
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- <TextBox Style="{StaticResource textBoxInError}"
- HorizontalAlignment="Left" Grid.Row="1"
- Width="100" Height="30"
- BorderThickness="2" BorderBrush="SpringGreen"
- >
- <TextBox.Text>
- <Binding
- RelativeSource="{
- RelativeSource FindAncestor,
- AncestorType={x:Type local:UserControl_Data_Validation}}"
- Path="MySubClassObj.MyDate_String"
- UpdateSourceTrigger="PropertyChanged"
- ValidatesOnDataErrors="True"
- />
- </TextBox.Text>
- </TextBox>
- <Button Content="Submit"
- Grid.Row="1"
- Width="100" Height="30" Click="Button_Click">
- <Button.Style>
- <Style TargetType="Button">
- <Setter Property="IsEnabled" Value="False"/>
- <Style.Triggers>
- <DataTrigger Value="{x:Static system:String.Empty}" >
- <Setter Property="IsEnabled" Value="True"/>
- <DataTrigger.Binding>
- <Binding
- RelativeSource="{
- RelativeSource FindAncestor,
- AncestorType={x:Type local:UserControl_Data_Validation}}"
- Path="MySubClassObj.Error"
- />
- </DataTrigger.Binding>
- </DataTrigger>
- </Style.Triggers>
- </Style>
- </Button.Style>
- </Button>
- <TextBlock x:Name="MyTextBlock"
- Grid.Column="1"
- Grid.Row="1"
- TextWrapping="Wrap"
- Text="Sumit here"
- />
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Globalization;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_Data_Validation.xaml
- /// </summary>
- public partial class UserControl_Data_Validation : UserControl
- {
- public UserControl_Data_Validation()
- {
- InitializeComponent();
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- MyTextBlock.Text = $"OK {MySubClassObj.MyDate_String}";
- }
- }
- public partial class UserControl_Data_Validation
- {
- static public readonly String NewLine = Environment.NewLine;
- public MySubClass MySubClassObj { get; set; } = new();
- public class MySubClass : IDataErrorInfo, INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler? PropertyChanged;
- public String MyDate_String
- {
- get => myDate_String;
- set => myDate_String = value;
- }
- public String this[string columnName]
- {
- get
- {
- String result = String.Empty;
- if (columnName == nameof(MyDate_String))
- {
- if (String.IsNullOrWhiteSpace(myDate_String))
- result = "Error:IsNullOrWhiteSpace" + Comment;
- else if (myDate_String.Length > 10) result = " Too long " + Comment;
- else try
- {
- DateTime _ =
- DateTime.ParseExact(myDate_String,
- "yyyy/MM/dd",
- System.Globalization.CultureInfo.InvariantCulture);
- }
- catch (Exception ex)
- {
- result = $"{ex.Message}{NewLine}" + Comment;
- }
- }
- Error = result;
- return result;
- }
- }
- private string _Error = "Error";
- public String Error
- {
- get
- {
- return _Error;
- }
- set
- {
- _Error = value;
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Error)));
- }
- }
- private string myDate_String = "2025/12/3";
- string Comment = $"{NewLine} Bad format.Using yyyy/MM/dd format";
- int _MyTestBindingRules;
- public int MyTestBindingRules
- {
- get
- {
- return _MyTestBindingRules;
- }
- set
- {
- _MyTestBindingRules = value;
- }
- }
- }
- }
- public class MyRangeRule : ValidationRule // TextBox
- {
- static public readonly String NewLine = Environment.NewLine;
- public int Min { get; set; }
- public int Max { get; set; }
- public override ValidationResult Validate(object value, CultureInfo cultureInfo)
- {
- try
- {
- int TMP = 0;
- string input = (string)value;
- if (String.IsNullOrWhiteSpace(input))
- return new ValidationResult(false,
- "The input is null or white sapce ");
- if (input.Length > 0)
- {
- TMP = int.Parse(input);
- }
- if (TMP > Max || TMP < Min)
- {
- return new ValidationResult(false,
- $"Out of Range{NewLine} Please Enter a number between {Min} and {Max}");
- }
- if (TMP == ExceptionNumber)
- {
- MessageBoxResult result =
- MessageBox.Show($"ExceptionNumber= {ExceptionNumber}", "Caprion", MessageBoxButton.YesNo);
- if (result == MessageBoxResult.Yes)
- throw new MyException();
- }
- }
- catch (MyException)
- {
- throw new MyException("ExceptionNumber");
- }
- catch (Exception ex)
- {
- return new ValidationResult(false,
- $"Illegal characters {NewLine} {ex.Message}");
- }
- return new ValidationResult(true, "ValidationResult Ok");
- }
- class MyException : Exception
- {
- public MyException() { }
- public MyException(string str) : base(str) { }
- }
- static int ExceptionNumber = 5; // RandomNumberGenerator.GetInt32(3);
- public static UpdateSourceExceptionFilterCallback ExceptionFilterCallback =
- new UpdateSourceExceptionFilterCallback(Source_ExceptionFilter2);
- static private Object Source_ExceptionFilter2(object bindExpression, Exception exception)
- {
- BindingExpression bindingExpression = (BindingExpression)bindExpression;
- Binding binding = bindingExpression.ParentBinding;
- binding.UpdateSourceExceptionFilter = new
- UpdateSourceExceptionFilterCallback(Source_ExceptionFilter3);
- MessageBox.Show($"binding.ValidatesOnExceptions= {binding.ValidatesOnExceptions}");
- //bindingExpression.UpdateSource();
- return $"2-->{exception.Message}";
- }
- static private Object Source_ExceptionFilter3(object obj, Exception exception)
- {
- return $"3-->{exception.Message}";
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_ListColorNames_class"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <UserControl.Resources>
- <CollectionViewSource
- Source="{Binding
- Source={x:Static local:UserControl_ListColorNames_class.AllItems}
- }"
- Filter="MyFilter"
- x:Key="MyCollectionViewSource">
- <CollectionViewSource.SortDescriptions>
- </CollectionViewSource.SortDescriptions>
- </CollectionViewSource>
- </UserControl.Resources>
- <Grid>
- <ListBox x:Name="MyListBox1"
- Height="320" Width="300" HorizontalAlignment="Left"
- SelectionChanged="ListBoxSelectionChanged1"
- ItemsSource="{Binding
- Source={StaticResource MyCollectionViewSource}}"
- DisplayMemberPath = "Name"
- />
- <ListBox x:Name="MyListBox2"
- Height="320" Width="300" HorizontalAlignment="Right"
- SelectionChanged="ListBoxSelectionChanged2"
- SelectedValuePath="Background"
- />
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_ListColorNames_class.xaml
- /// </summary>
- ///
- public partial class UserControl_ListColorNames_class : UserControl
- {
- public UserControl_ListColorNames_class()
- {
- InitializeComponent();
- //MyListBox1.ItemsSource = AllItems;
- for (int ii = 0; ii < AllItems.Count; ii++)
- {
- //MyListBox1.Items.Add(NamedColor.All[ii]);
- }
- //MyListBox1.SelectedValuePath = nameof(NamedColor.Color_Value);
- //MyListBox1.DisplayMemberPath = nameof(NamedColor.Name);
- }
- void MyFilter(object sender, FilterEventArgs e)
- {
- NamedColor SS = (NamedColor)e.Item;
- if (SS.Name.Length < 26) e.Accepted = true;
- else
- {
- e.Accepted = false;
- }
- }
- //#pragma warning disable CS0660 // Type defines operator == or operator != but does not override Object.Equals(object o)
- //#pragma warning disable CS0661 // Type defines operator == or operator != but does not override Object.GetHashCode()
- #pragma warning disable CS0660, CS0661
- public class MyLabel : System.Windows.Controls.Label
- #pragma warning restore CS0661 // Type defines operator == or operator != but does not override Object.GetHashCode()
- #pragma warning restore CS0660 // Type defines operator == or operator != but does not override Object.Equals(object o)
- {
- public static bool operator ==(MyLabel left, MyLabel right)
- {
- return ((String)(left.Content)).CompareTo(((MyLabel)right).Content) == 0;
- }
- public static bool operator !=(MyLabel left, MyLabel right)
- {
- return !(left == right);
- }
- }
- void ListBoxSelectionChanged1(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- if (listBox.SelectedIndex >= 0)
- {
- var GotNamedColor = (NamedColor)listBox.SelectedValue;
- Background = new SolidColorBrush(GotNamedColor.Color_Value);
- if (MyListBox2 == null) return;
- MyLabel label = new()
- {
- Background = new SolidColorBrush(GotNamedColor.Color_Value),
- Content = GotNamedColor.Name2
- };
- var myLabels = from MyLabel n in MyListBox2.Items
- where n == label
- select n;
- if (myLabels.Any())
- {
- label = myLabels.Single();
- }
- else MyListBox2.Items.Add(label);
- MyListBox2.ScrollIntoView(label);
- }
- }
- void ListBoxSelectionChanged2(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- if (listBox.SelectedIndex >= 0)
- {
- //MessageBox.Show(listBox.SelectedValue.GetType().ToString());
- Background = (SolidColorBrush)listBox.SelectedValue;
- }
- }
- public class MyObservableCollection : ObservableCollection<NamedColor>
- {
- }
- public static MyObservableCollection AllItems
- {
- get => NamedColor.All;
- }
- public class NamedColor
- {
- int ID;
- string Color_PropertyInfo_Name = string.Empty;
- Color _color;
- static MyObservableCollection namedColors;
- static NamedColor()
- {
- PropertyInfo[] propertyInfo = typeof(Colors).GetProperties();
- namedColors = new MyObservableCollection();
- for (int ii = 0; ii < propertyInfo.Length; ii++)
- namedColors.Add(
- new NamedColor()
- {
- ID = ii,
- Color_PropertyInfo_Name = propertyInfo[ii].Name,
- _color = (Color)(propertyInfo[ii].GetValue(null) ??
- throw new Exception($"{ii}:_color == null"))
- }
- );
- }
- public static MyObservableCollection All
- {
- get { return namedColors; }
- }
- public Color Color_Value { get { return _color; } }
- public string Name
- {
- get
- {
- StringBuilder strSpaced = new($"{ID,4}:{_color} >> {Color_PropertyInfo_Name[0]}");
- for (int ii = 1; ii < Color_PropertyInfo_Name.Length; ii++)
- strSpaced.
- Append((Char.IsUpper(Color_PropertyInfo_Name[ii]) ? " " : "")).
- Append(Color_PropertyInfo_Name[ii]);
- return strSpaced.ToString();
- }
- }
- public string Name2
- {
- get => $"{ID,4}:{Color_PropertyInfo_Name}";
- }
- public override string ToString()
- {
- return Color_PropertyInfo_Name;
- }
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_ListColorNames_item"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <Grid x:Name="MyGrid">
- <ListBox Height="450" Width="320"
- x:Name="MyListBox_item"
- SelectionChanged="ListBoxSelectionChanged_item"
- SelectedValuePath="Background"
- SelectedValue="{Binding Path=Background,
- ElementName=MyGrid}"/>
- <!--
- SelectedValue="{Binding Path=Background}"
- DataContext="{x:Reference Name=MyGrid}"/>
- -->
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_ListColorNames_item.xaml
- /// </summary>
- public partial class UserControl_ListColorNames_item : UserControl
- {
- public UserControl_ListColorNames_item()
- {
- InitializeComponent();
- MyInitialize();
- }
- void MyInitialize()
- {
- PropertyInfo[] propertyInfo = typeof(Colors).GetProperties();
- for (int ii = 0; ii < propertyInfo.Length; ii++)
- {
- var item = new ListBoxItem()
- {
- Content = Name_item(propertyInfo[ii].Name, ii),
- Background = new SolidColorBrush((Color)
- (propertyInfo[ii].GetValue(null) ??
- throw new Exception($"{ii}:_color == null")
- )
- ),
- };
- MyListBox_item.Items.Add(item);
- }
- //MyListBox_item.SetBinding(
- // ListBox.SelectedNumericUpDown_ValueProperty, nameof(Background));
- //MyListBox_item.DataContext = this;
- //MyListBox_item.SelectedValuePath = nameof(ListBoxItem.Background);
- }
- static public string Name_item(string label_Name, int ID)
- {
- StringBuilder strSpaced = new($"{ID,4}:{label_Name[0]}");
- for (int ii = 1; ii < label_Name.Length; ii++)
- strSpaced.
- Append((Char.IsUpper(label_Name[ii]) ? " " : "")).
- Append(label_Name[ii]);
- return strSpaced.ToString();
- }
- void ListBoxSelectionChanged_item(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- if (listBox.SelectedIndex >= 0)
- {
- // this.Background = ((ListBoxItem)listBox.SelectedValue).Background;
- //MessageBox.Show($"{listBox.SelectedIndex}");
- }
- if (e.RemovedItems.Count > 0)
- {
- var item = (ListBoxItem)(e.RemovedItems[0] ?? throw new Exception());
- item.FontSize /= 2;
- }
- if (e.AddedItems.Count > 0)
- {
- var item = (ListBoxItem)(e.AddedItems[0] ?? throw new Exception());
- item.FontSize *= 2;
- }
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_ListColorNames_label"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <Grid>
- <ListBox Height="400" Width="320"
- x:Name="MyListBox"
- SelectionChanged="ListBoxSelectionChanged_label"
- />
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_ListColorNames_label.xaml
- /// </summary>
- public partial class UserControl_ListColorNames_label : UserControl
- {
- public UserControl_ListColorNames_label()
- {
- InitializeComponent();
- MyInitialize();
- }
- void MyInitialize()
- {
- PropertyInfo[] propertyInfo = typeof(Colors).GetProperties();
- for (int ii = 0; ii < propertyInfo.Length; ii++)
- {
- var label = new Label()
- {
- Content = Name2(propertyInfo[ii].Name, ii),
- Background = new SolidColorBrush(
- (Color)(propertyInfo[ii].GetValue(null) ??
- throw new Exception($"{ii}:_color == null")
- ))
- };
- MyListBox.Items.Add(label);
- }
- }
- void ListBoxSelectionChanged_label(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- if (listBox.SelectedIndex >= 0)
- {
- this.Background = ((Label)listBox.SelectedValue).Background;
- }
- }
- static public string Name2(string label_Name, int ID)
- {
- StringBuilder strSpaced = new($"{ID,4}:{label_Name[0]}");
- for (int ii = 1; ii < label_Name.Length; ii++)
- strSpaced.
- Append((Char.IsUpper(label_Name[ii]) ? " " : "")).
- Append(label_Name[ii]);
- return strSpaced.ToString();
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_ListColorNames_string"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <UserControl.Resources>
- <local:String_And_BrushConverter x:Key="String_And_BrushConverterKey"/>
- </UserControl.Resources>
- <Grid>
- <ListBox Height="320" Width="320"
- ItemsSource="{x:Static
- local:UserControl_ListColorNames_string.ColorPropertyNames}"
- SelectionChanged="ListBoxSelectionChanged"
- x:Name="ListBox_string" >
- <ListBox.SelectedItem>
- <Binding Path="Background"
- Source="{x:Reference MyLabel_1_in_UserControl_ListColorNames_string}"
- Converter="{StaticResource String_And_BrushConverterKey}"/>
- </ListBox.SelectedItem>
- <!--
- Converter="{x:Static
- local:UserControl_ListColorNames_string.MyTestConverter}"/>
- -->
- </ListBox>
- <TextBlock Height="30" Width="100"
- HorizontalAlignment="Left" VerticalAlignment="Top"
- Text="TextBlock_1"
- x:Name="TextBlock_1_in_UserControl_ListColorNames_string">
- <TextBlock.Background>
- <Binding Path="SelectedItem"
- Source="{x:Reference ListBox_string}"
- Converter="{StaticResource String_And_BrushConverterKey}"
- ConverterParameter="AAA"/>
- </TextBlock.Background>
- </TextBlock>
- <TextBlock Height="30" Width="100"
- HorizontalAlignment="Right" VerticalAlignment="Top"
- Background="LawnGreen"
- x:Name="TextBlock_2_in_UserControl_ListColorNames_string">
- <TextBlock.Text>
- <Binding Path="SelectedIndex"
- Source="{x:Reference ListBox_string}"
- Converter="{x:Static
- local:UserControl_ListColorNames_string.MyGet_String}"
- ConverterParameter="{x:Reference ListBox_string}"
- />
- </TextBlock.Text>
- </TextBlock>
- <Label Height="30" Width="100"
- HorizontalAlignment="Left" VerticalAlignment="Bottom"
- Content="MyLabal_1" Background="Yellow"
- x:Name="MyLabel_1_in_UserControl_ListColorNames_string"
- />
- <Label Height="30" Width="100"
- HorizontalAlignment="Right" VerticalAlignment="Bottom"
- Content="MyLabal_2"
- FontWeight="ExtraBold"
- Background="{DynamicResource
- {x:Static SystemColors.AccentColorLight3BrushKey}}"
- x:Name="MyLabel_2_in_UserControl_ListColorNames_string"
- />
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_ListColorNames_string.xaml
- /// </summary>
- ///
- public partial class UserControl_ListColorNames_string : UserControl
- {
- public UserControl_ListColorNames_string()
- {
- InitializeComponent();
- this.Background = new SolidColorBrush(Colors.Red);
- //ListBox_string.SetBinding(
- // ListBox.SelectedItemProperty, nameof(Background));
- //ListBox_string.DataContext = this;
- //ListBox_string.DataContext = MyLabel_1_in_UserControl_ListColorNames_string;
- }
- private static string[] _ColorPropertyNames = Array.Empty<string>();
- public static string[] ColorPropertyNames
- {
- get
- {
- if (_ColorPropertyNames != Array.Empty<string>())
- {
- return _ColorPropertyNames;
- }
- int ii = 0;
- PropertyInfo[] propertyInfo = typeof(Colors).GetProperties();
- _ColorPropertyNames = new string[propertyInfo.Length];
- foreach (PropertyInfo color_propertyInfo in propertyInfo)
- {
- _ColorPropertyNames[ii++] = color_propertyInfo.Name;
- }
- return _ColorPropertyNames;
- }
- }
- void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- ListBox listBox = (ListBox)sender;
- if (listBox.SelectedIndex >= 0)
- {
- var SelectedColor = (String)(listBox.Items[listBox.SelectedIndex]);
- var color_propertyInfo = typeof(Colors).GetProperty(SelectedColor);
- if (color_propertyInfo != null)
- {
- var color = (Color)
- (color_propertyInfo.GetValue(null) ?? throw new Exception());
- MyLabel_2_in_UserControl_ListColorNames_string.Foreground = new SolidColorBrush(color);
- }
- }
- }
- static public IValueConverter MyTestConverter = new String_And_BrushConverter();
- static public IValueConverter MyGet_String = new Get_String();
- }
- [ValueConversion(typeof(Brush), typeof(string))]
- public class String_And_BrushConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- BrushConverter brushConverter = new();
- string MyBrush_Str = brushConverter.ConvertToInvariantString(value) ??
- throw new Exception();
- //MessageBox.Show("Convert : " + parameter);
- return MyBrush_Str;
- }
- public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- BrushConverter brushConverter = new();
- Brush? MyBrush = (Brush?)brushConverter.ConvertFromString((string)value);
- //MessageBox.Show("ConvertBack : " + parameter);
- return MyBrush is null ?
- throw new NoNullAllowedException("String_And_BrushConverter")
- : (object)MyBrush;
- }
- }
- public class Get_String : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- string MyString = "TextBlock_2";
- var listBox = (ListBox)parameter;
- if (listBox.SelectedIndex >= 0) MyString =
- $"{listBox.SelectedIndex}:{listBox.Items[listBox.SelectedIndex]}";
- return MyString;
- }
- public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException("Get_String.ConvertBack");
- }
- }
- }
- <UserControl x:Class="WpfControlLibrary_Hello.UserControl_NumericUpDown"
- 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:WpfControlLibrary_Hello"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <Grid Background="Yellow">
- <Grid.RowDefinitions>
- <RowDefinition/>
- <RowDefinition/>
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition/>
- <ColumnDefinition/>
- <ColumnDefinition/>
- </Grid.ColumnDefinitions>
- <TextBlock Width="150" Height="30" Background="Red"
- TextAlignment="Center">
- <TextBlock.Text>
- <Binding
- RelativeSource="{RelativeSource FindAncestor,
- AncestorType={x:Type local:UserControl_NumericUpDown}}"
- Path="NumericUpDown_Value">
- </Binding>
- </TextBlock.Text>
- </TextBlock>
- <Button Width="130" Height="20" Grid.Row="1"
- Content="Trace" Click="Button_Click" />
- <RepeatButton Name="upButton" Click="upButton_Click"
- Background="Green" Width="100" Height="20"
- Grid.Column="1" Grid.Row="0">Up</RepeatButton>
- <RepeatButton Name="downButton" Click="downButton_Click"
- Background="Lime" Width="100" Height="20"
- Grid.Column="1" Grid.Row="1">Down</RepeatButton>
- <TextBlock x:Name="MyTrace" Grid.Column="2" Grid.RowSpan="2"/>
- </Grid>
- </UserControl>
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- 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 WpfControlLibrary_Hello
- {
- /// <summary>
- /// Interaction logic for UserControl_NumericUpDown.xaml
- /// </summary>
- ///
- public partial class UserControl_NumericUpDown : UserControl
- {
- public UserControl_NumericUpDown()
- {
- InitializeComponent();
- }
- /// Identifies the NumericUpDown_Value dependency property.
- public static readonly DependencyProperty NumericUpDown_ValueProperty =
- DependencyProperty.Register(
- nameof(NumericUpDown_Value), typeof(decimal), typeof(UserControl_NumericUpDown),
- new FrameworkPropertyMetadata(2m,
- new PropertyChangedCallback(OnValueChanged),
- new CoerceValueCallback(CoerceValue)));
- //new CoerceValueCallback(CoerceValue)));
- /// Identifies the ValueChanged routed event.
- public static readonly RoutedEvent ValueChangedEvent =
- EventManager.RegisterRoutedEvent(
- nameof(ValueChanged), RoutingStrategy.Bubble,
- typeof(RoutedPropertyChangedEventHandler<decimal>),
- typeof(UserControl_NumericUpDown));
- /// Gets or sets the value assigned to the control.
- public decimal NumericUpDown_Value
- {
- get { trace("get NumericUpDown_Value"); return (decimal)GetValue(NumericUpDown_ValueProperty); }
- set { trace("set NumericUpDown_Value"); SetValue(NumericUpDown_ValueProperty, value); }
- }
- public const decimal MinValue = 0;
- public const decimal MaxValue = 10;
- private static object CoerceValue(DependencyObject element, object value)
- {
- trace("CoerceValue");
- var control = (UserControl_NumericUpDown)element;
- decimal newValue = (decimal)value;
- newValue = Math.Max(MinValue, Math.Min(MaxValue, newValue));
- return newValue;
- }
- private static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
- {
- trace("OnValueChanged");
- var control = (UserControl_NumericUpDown)obj;
- var e = new RoutedPropertyChangedEventArgs<decimal>(
- (decimal)args.OldValue, (decimal)args.NewValue, ValueChangedEvent);
- control.OnValueChanged(e);
- }
- /// Occurs when the NumericUpDown_Value property changes.
- public event RoutedPropertyChangedEventHandler<decimal> ValueChanged
- {
- add { trace("add AddHandler"); AddHandler(ValueChangedEvent, value); }
- remove { trace("remove AddHandler"); RemoveHandler(ValueChangedEvent, value); }
- }
- /// Raises the ValueChanged event.
- /// <param name="args">Arguments associated with the ValueChanged event.</param>
- protected virtual void OnValueChanged(RoutedPropertyChangedEventArgs<decimal> args)
- {
- trace("RaiseEvent");
- RaiseEvent(args);
- }
- private void upButton_Click(object sender, EventArgs e)
- {
- trace("*********** upButton_Click ***********");
- NumericUpDown_Value++;
- trace("*********** upButton_Click ***********");
- }
- private void downButton_Click(object sender, EventArgs e)
- {
- trace("******* downButton_Click *********");
- NumericUpDown_Value--;
- trace("******* downButton_Click *********");
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- MyTrace.Text = _Tracer.ToString(); _Tracer.Clear();
- }
- static StringBuilder _Tracer = new StringBuilder();
- public static void trace(string message) { _Tracer.AppendLine(message); }
- }
- }














































































































































































































































留言
張貼留言