页面 1 2 if (NavigationService.CanGoBack == true ) NavigationService.GoBack();NavigationService.Navigate(new Uri("Page.xaml" ,UriKind.Relative));
打印对话框PrintDialog 如果要一下启动两个窗口,可以重写App.cs中的OnStartUP方法 设置窗口所属关系,窗体A.Owner=窗体B 单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public partial class App : Application { protected override void OnStartup (StartupEventArgs e ) { base .OnStartup(e); Mutex mutex = new Mutex(true , "MainWindow" , out bool isNewInstance); if (!isNewInstance ) { IntPtr intPtr = FindWindowW(null , "MainWindow" ); if (intPtr !=IntPtr.Zero) { SetForegroundWindow(intPtr); } Shutdown(); } } [DllImport("User32" , CharSet = CharSet.Unicode) ] static extern IntPtr FindWindowW (string ClassName, string WindowName ) ; [DllImport("User32" , CharSet = CharSet.Unicode) ] static extern bool SetForegroundWindow (IntPtr hWnd ) ; }
启动参数同样是在OnStartup函数中设置string[] args = e.Args;
异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 protected override void OnStartup (StartupEventArgs e ){ base .OnStartup(e); DispatcherUnhandledException += App_DispatcherUnhandledException; } private void App_DispatcherUnhandledException (object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e ){ e.Handled = true ; } public MainWindow (){ InitializeComponent(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } private void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e ){ MessageBox.Show("dd" ); }
Label TextBlock合理Label相比,更加轻量化,Lable常用在可以连接到指定地方,加下划线。
Image img.Source = new ImageSourceConverter().ConvertFromString("path.png") as ImageSource;
这种方式需要设置图片不能为资源img.Source = new BitmapImage(new Uri("path.png", UriKind.RelativeOrAbsolute));
对DataGrid数据进行排序 1 2 3 4 5 6 7 var cvs= CollectionViewSource.GetDefaultView(dataGrid.ItemsSource); if (cvs!=null && cvs.CanSort) { cvs.SortDescriptions.Clear(); cvs.SortDescriptions.Add(new System.ComponentModel.SortDescription("Name" , System.ComponentModel.ListSortDirection.Descending)); }
对DataGrid数据进行分组 1 2 3 4 5 6 7 var cvs= CollectionViewSource.GetDefaultView(dataGrid.ItemsSource); if (cvs!=null && cvs.CanGroup) { cvs.GroupDescriptions.Clear(); cvs.GroupDescriptions.Add(new PropertyGroupDescription("Group" )); }
对DataGrid数据进行筛选 1 2 3 4 5 6 7 8 9 10 11 12 13 var cvs= CollectionViewSource.GetDefaultView(dataGrid.ItemsSource); if (cvs!=null && cvs.CanFilter) { cvs.Filter = (obj) => { if (obj is Person per) { return per.FirstName.Contans("TOM" ); } return false ; }; }
使用行为来扩展控件的功能 nuget安装System.Windows.Interactivity.WPF
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class GrowTextBehavior :Behavior <TextBlock >{ public int Size { get ; set ; } protected override void OnAttached () { base .OnAttached(); AssociatedObject.MouseEnter += AssociatedObject_MouseEnter; AssociatedObject.MouseLeave += AssociatedObject_MouseLeave; } protected override void OnDetaching () { base .OnDetaching(); AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter; AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave; } private void AssociatedObject_MouseLeave (object sender, System.Windows.Input.MouseEventArgs e ) { AssociatedObject.FontSize -= Size; } private void AssociatedObject_MouseEnter (object sender, System.Windows.Input.MouseEventArgs e ) { AssociatedObject.FontSize += Size; } }
XAML1 2 3 4 5 6 7 8 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" <StackPanel VerticalAlignment ="Center" > <TextBlock HorizontalAlignment ="Center" VerticalAlignment ="Center" Text ="HHHH" > <i:Interaction.Behaviors > <local:GrowTextBehavior Size ="10" /> </i:Interaction.Behaviors > </TextBlock > </StackPanel >
使用DLL中的资源 Source="/LibraryName;component/Images/img.jpg"
在代码中访问Application.GetRemoteStream(new Uri("/MyLib;component/Img/R-C.png", UriKind.RelativeOrAbsolute));
资源管理 在Application.Resources中合并其他资源字典
使用系统的颜色和字体 {DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}
其他线程更新UI 1 2 3 4 5 6 7 8 9 ThreadPool.QueueUserWorkItem(_ => { Dispatcher.BeginInvoke(new Action(()=> { this .btn.Content = "aa" ; })); });
BackgroundWorker组件 1 2 3 4 5 6 7 8 BackgroundWorker worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true ; worker.DoWork += Worker_DoWork; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; worker.RunWorkerAsync(new Tuple<int , int >(1 , 2 )); worker.WorkerReportsProgress = true ; worker.ProgressChanged += Worker_ProgressChanged; worker.CancelAsync();
定时更新界面 1 2 3 4 DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Interval = TimeSpan.FromSeconds(1.0 ); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Start();
加入引用WindowsFormsIntegration和System.Windows.Forms
xaml中
1 2 3 <WindowsFormsHost > <forms:PropertyGrid x:Name ="proForms" /> </WindowsFormsHost >
proForms.SelectedObject = txtWPF;
直接拖控件
WPF如何将DLL嵌入到exe文件中 1)使用第三方库的WPF应用程序 2)修改项目文件
1 2 3 4 5 6 7 <Target Name ="AfterResolveReferences" > <ItemGroup > <EmbeddedResource Include ="@(ReferenceCopyLocalPaths)" Condition ="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'" > <LogicalName > %(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName > </EmbeddedResource > </ItemGroup > </Target >
3)修改App.Xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 private static Assembly OnResolveAssembly (object sender, ResolveEventArgs args ) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); var executingAssemblyName = executingAssembly.GetName(); var resName = executingAssemblyName.Name + ".resources" ; AssemblyName assemblyName = new AssemblyName(args.Name); string path = "" ; if (resName == assemblyName.Name) { path = executingAssemblyName.Name + ".g.resources" ; ; } else { path = assemblyName.Name + ".dll" ; if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false ) { path = String.Format(@"{0}\{1}" , assemblyName.CultureInfo, path); } } using (Stream stream = executingAssembly.GetManifestResourceStream(path)) { if (stream == null ) return null ; byte [] assemblyRawBytes = new byte [stream.Length]; stream.Read(assemblyRawBytes, 0 , assemblyRawBytes.Length); return Assembly.Load(assemblyRawBytes); } } protected override void OnStartup (StartupEventArgs e ) { base .OnStartup(e); AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly; }
C#调用win32API参考网站http://www.pinvoke.net