WPF显示控件时出现虚边

当你用WPF显示控件时,时不时会发现控件或字体出现虚虚的状态。例如:DataGrid的Header,一栏显示得很清晰,隔壁显示的就有些模糊。查了下资料,是因为WPF编程是与特理显示设备无关,用的是逻辑单位。这个逻辑单位在转换成特理单位的过程中,比如转换成像素点的时候,可以出现小数,比如:0.5像素,这个时候是没有办法在特理设备上显示的,所以WPF的策略是在它的两边以虚框显示。这样对于整体来讲就是虚虚地。若想解决这个问题,最好的方式是加上UseLayoutRounding,如果这个特性不能解决问题,就可以控件中把SnapsToDevicePixels特性加上。Stackoverflow上的一个回答是建议用UseLayoutRounding。

Good answers by Spencer and Martin as to the when to align your pixels.

As to the how: I would also point out that one should in WPF 4.0 try using the property UseLayoutRounding instead of SnapsToDevicePixels.

UseLayoutRounding makes what you are doing compatible with Silverlight (SnapsToDevicePixels is not available in Silverlight) ... and Microsoft is also encouraging the use of UseLayoutRounding over SnapsToDevicePixels in its documentation.

What is the difference between the two? Well, one big difference is that UseLayoutRounding occurs during the layout phase while SnapsToDevicePixels occurs during the render phase. This makes me speculate that UseLayoutRounding is probably a more performant way to go (I haven't confirmed this, though).

All that being said, there will still be reasons to use SnapsToDevicePixels. In fact, the MSDN documentation points to one. I will add another: it is only with SnapsToDevicePixels that you can use guidelines for precise control.

Here are some resources on this matter (i.e. pixel snapping and clarity with images, text, and visuals):

Heh. I know my answer was a little more than what you were asking for ... but this concept (i.e. resolution independence and the resulting problems it brings and how to get over them) can often be a point of frustration when working with WPF. At the very least, I wanted to point you to the new WPF 4.0 property, UseLayoutRounding.

UPDATE

I just have to add since I've seen this over and over ... sometimes SnapsToDevicePixels works when UseLayoutRounding doesn't. I wish I could put a finger on why this is the case, but definitely try UseLayoutRounding first and if that doesn't work, don't hesitate to try SnapsToDevicePixels.

请参考 :http://stackoverflow.com/questions/2399731/when-should-i-use-snapstodevicepixels-in-wpf-4-0

原文地址:https://www.cnblogs.com/sdikerdong/p/3427570.html