论WPF中的那些坑

1.WPF中AllowsTransparency和WebBrowser兼容性问题
(1)利用WindowChrome设置GlassFrameThickness属性为-1,而不设置AllowsTransparency来达到背景透明效果:
参考网址:点击跳转至相应网页
示例代码(前台xmal代码):

<Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            WindowStyle="None" ResizeMode="CanMinimize"
            Title="walterlv demo" Height="450" Width="800">
    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="-1" />
    </WindowChrome.WindowChrome>
    <Window.Template>
        <ControlTemplate TargetType="Window">
            <Border Padding="20">
                <Border.Background>
                    <ImageBrush ImageSource="Image/123.png"/>
                </Border.Background>               
            </Border>
        </ControlTemplate>
    </Window.Template>
    <Grid>        
    </Grid>
</Window>

(2)通过调用系统api,将窗体透明
解决方法:点击跳转至相应网页
下面进行简述:
将window 的 AllowsTransparenc属性设为false,将下述代码放置于window类的代码里

protected override void OnSourceInitialized(EventArgs e)
{
  base.OnSourceInitialized(e);
  // This can't be done any earlier than the SourceInitialized event:
  GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
}

即可解决问题,其中GlassHelper.ExtendGlassFrame的代码如下:

public class GlassHelper
{
  [DllImport("dwmapi.dll", PreserveSig=false)]
  static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

  [DllImport("dwmapi.dll", PreserveSig=false)]
  static extern bool DwmIsCompositionEnabled();

  public static bool ExtendGlassFrame(Window window, Thickness margin)
  {
    if (!DwmIsCompositionEnabled())
      return false;


    IntPtr hwnd = new WindowInteropHelper(window).Handle;
    if (hwnd == IntPtr.Zero)
      throw new InvalidOperationException("The Window must be shown before extending glass.");


    // Set the background to transparent from both the WPF and Win32 perspectives
    window.Background = Brushes.Transparent;
    HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;


    MARGINS margins = new MARGINS(margin);
    DwmExtendFrameIntoClientArea(hwnd, ref margins);
    return true;
  }
}
struct MARGINS 
{
  public MARGINS(Thickness t)
  {
    Left = (int)t.Left;
    Right = (int)t.Right;
    Top = (int)t.Top;
    Bottom = (int)t.Bottom;
  }
  public int Left;
  public int Right;
  public int Top;
  public int Bottom;
}

2.WPF中WebBrowser控件因其置顶的原因无法让其他控件叠加上去
解决方法:点击跳转至相应网页

3.WPF中经常出现相对路径找不到图片位置的,那么需要先考虑是否图片包含在项目中、是否图片属性为Resource,如果仍不行,那么就将图片路径写成绝对路径,如下所示:

var bitmap = new BitmapImage(new Uri("pack://application:,,,/Images/123.png", UriKind.Absolute));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值