WPF-页面-DataGrid数据处理-多线程-Winform嵌入

WPF-页面-DataGrid数据处理-多线程-Winform嵌入

页面

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");
}
//异常首先被程序级别捕获再传到窗口级别,如果在程序级别中不设置e.Handled = true;则会传到窗口级别,然后主程序挂掉。
//所以在主程序挂掉之前要重启

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;
};
}

使用行为来扩展控件的功能

  1. nuget安装System.Windows.Interactivity.WPF
  2. 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;
    }
    }

  3. XAML
    1
    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(_ =>
{
//其他现成更新UI
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();

WPF中放入Winform控件

加入引用WindowsFormsIntegration和System.Windows.Forms
xaml中

1
2
3
<WindowsFormsHost>
<forms:PropertyGrid x:Name="proForms"/>
</WindowsFormsHost>

proForms.SelectedObject = txtWPF;

Winform中放入WPF控件

直接拖控件

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

WPF-页面-DataGrid数据处理-多线程-Winform嵌入

https://bubuweiying.site/WPF-页面-DataGrid数据处理-多线程-Winform嵌入/

作者

步步为营

发布于

2024-05-08

更新于

2025-03-15

许可协议