分类 WPF 下的文章

背景

写了个wpf程序,需要在服务器上运行一下,开发的时候使用的net core 3.1,服务器上未安装,安装需要重启电脑,明显不可以。

解决

将wpf打包成自宿主的程序,包含所有运行环境一块打包出来。

打包方法

在项目目录下执行如下命令:

dotnet publish -r win-x64 -c Release --self-contained

这里配置了程序在Windows 64位下运行。

提示如下表示已经生成完成了,直接拷贝

PS F:\test> dotnet publish -r win-x64 -c Release --self-contained
用于 .NET 的 Microsoft (R) 生成引擎版本 17.0.0-preview-21501-01+bbcce1dff
版权所有(C) Microsoft Corporation。保留所有权利。

  正在确定要还原的项目…
  所有项目均是最新的,无法还原。
  你正在使用 .NET 的预览版。请查看 https://aka.ms/dotnet-core-preview
  test -> F:\test\bin\Release\netcoreapp3.1\win-x64\test.dll
  test -> F:\test\bin\Release\netcoreapp3.1\win-x64\publish\
PS F:\test>

拷贝到服务器上,双击打开直接使用即可,无需再安装运行时。

<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Setter Property="Background" Value="{x:Null}"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Background" Value="White"/>
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect BlurRadius="20" Opacity="0.3" ShadowDepth="0" Color="#19334E"/>
                </Setter.Value>
            </Setter>
        </Style>
    </Border.Style>
    <Image Width="1080" Height="720"  Source="Imgs/01.png" />
</Border>

效果图如下:

带阴影效果的图片.png

wpf获取某一属性的绑定信息

背景

WPF开发时,常常会将一些属性进行数据绑定,如某一控件A的宽高属性。然而,有些操作可能会覆盖掉该绑定,如全屏操作,基于一些原因,该操作需要手动修改控件宽高,这时,控件的绑定属性将失效,在取消全屏时,如不做处理,控件A的宽高将无法正常设置。

解决方案

全屏时,在需要手动设置控件A的宽高属性之前,手动保存宽高的绑定信息。

mb_height_multi = BindingOperations.GetMultiBindingExpression((_textbox as TextBox), EmbryologySlide.HeightProperty);

在取消全屏时,重新将宽高属性设置回绑定。

_textbox.SetBinding(TextBox.HeightProperty, mb_height_multi.ParentMultiBinding);

以上是以多条件绑定为例,如是单条件绑定,如下:

mb_height = BindingOperations.GetBindingExpression((_textbox as TextBox), EmbryologySlide.HeightProperty);
。。。
_textbox.SetBinding(TextBox.HeightProperty, mb_height?.ParentBinding);

其他操作

  • 获取Binding/MultiBinding

    MultiBindingExpression mbe = BindingOperations.GetMultiBindingExpression((child as TextBox), TextBox.TextProperty);
  • 拿到其中每个Binding的Path

    Binding bd = mbe.ParentMultiBinding.Bindings[0] as Binding;
    bindingPath = bd.Path.Path;
  • 拿到其中的ValidationRule

    ValidationRule vr = mbe.ParentMultiBinding.ValidationRules[0];
  • 更新MultiBinding

    mbe.UpdateSource();

总结

当然,大部分情况下,只要设计合理,类似全屏之类的操作,是不需要修改类似宽高之类的属性信息的。但一些特殊情况,如对自定义控件全屏,且全屏时,需要将控件移动至新窗体实现。此时若自定义控件高度绑定在了原窗体的数据或控件属性上。就需要用到本文方案了。