读书人

WPF自定义窗体为何右边没有光标呢

发布时间: 2013-09-15 19:58:13 作者: rapoo

WPF,自定义窗体,为什么右边没有光标呢?
摘自:http://www.cnblogs.com/zhoujg/archive/2010/08/17/1801271.html

参照博客园中的文章,现在写一个简单的自定义窗体:


<Window x:Class="WPF熊俊.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF熊俊"
AllowsTransparency="True" WindowStyle="None" Background="Transparent"
Style="{DynamicResource Mainwindow}" WindowStartupLocation="CenterScreen" >
<Window.Resources>
<ControlTemplate x:Key="ResizeDecoratorTemplate" TargetType="Control">
<Grid>
<local:ResizeThumb Height="3" Cursor="SizeNS" Margin="0 -4 0 0"
VerticalAlignment="Top" HorizontalAlignment="Stretch"/>
<local:ResizeThumb Width="3" Cursor="SizeWE" Margin="-4 0 0 0"
VerticalAlignment="Stretch" HorizontalAlignment="Left"/>
<local:ResizeThumb Width="3" Cursor="SizeWE" Margin="0 0 -4 0"
VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
<local:ResizeThumb Height="3" Cursor="SizeNS" Margin="0 0 0 -4"
VerticalAlignment="Bottom" HorizontalAlignment="Stretch"/>
</Grid>
</ControlTemplate>
<Style x:Key="Mainwindow" TargetType="{x:Type Window}">
<Setter Property="Template">
<Setter.Value>


<ControlTemplate TargetType="{x:Type Window}">
<Border BorderThickness="1" BorderBrush="Red" Background="#FFD4DEBF">
<Grid>
<Control Template="{StaticResource ResizeDecoratorTemplate}"/>
<ContentPresenter />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
</Window>




public class ResizeThumb:Thumb
{
public ResizeThumb()
{
...
...
}
}


启动窗体后,鼠标移到四周,为什么只有左边、上边能看到变样的鼠标光标,而右边和下边始终看不到变样的光标呢?上、下、左、右的代码不都是一样的吗?折腾了好几天了,找不到原因


[解决办法]
这个是wpf的off-by-one bug,就是鼠标的检测范围比实际的图形要大1个像素(分别在右边和下边)。
因为在wpf的HitTestCore中调用Rect.Contains(),而Rect.Contains长宽多算了一个像素。

你的程序实际上已经把四个thumb都彻底移出了border(margin=-4),而上边和左边利用了这个bug/特性,所以鼠标有反应。

正确的做法是不要把thumb移出border,如果不想看到thumb,可以给thumb重新做个template。
[解决办法]
学习学习额。。。。。
[解决办法]
thumb在border里面还套了两个border,为了做出立体效果。
不想做template的话,可以在thumb所在的grid里加上这些资源:


<Grid.Resources>
<Style TargetType="Thumb">
<Setter Property="Background" Value="Transparent" />
</Style>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkDarkBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlLightLightBrushKey}" Color="Transparent"/>
</Grid.Resources>
其实改模板的话代码还少两行。
[解决办法]
引用 MSDN:
获取当用户使用鼠标拖动 Thumb 控件时,鼠标自上一 DragDelta 事件以来移动的水平距离。

http://msdn.microsoft.com/zh-cn/library/system.windows.controls.primitives.dragdeltaeventargs.horizontalchange(v=vs.90).aspx
[解决办法]
本次的终点相对于上次的终点的距离。
x从左向右为正方向,y从上向下为正方向。

读书人网 >C#

热点推荐