【WPF】Binding's Little Trick

博客解决了在WPF中使用3D PerspectiveCamera时遇到的绑定问题,通过修改XAML中的绑定方式避免了因对象冻结导致的错误。

今天为了帮别人解决一个3D的问题,需要将自己以前做的一个Demo发过去,结果,原来能正常运行的程序现在无法运行了。调试时报出的错误是:

“无法将“System.Windows.Media.Media3D.PerspectiveCamera”值分配到对象“System.Windows.Controls.Viewport3D”的属性“Camera”。 由于自其创建后已设置一个或多个本地值,因此当前本地值枚举已过时。  标记文件“Test3D;component/window1.xaml”中行45位置 19 的对象“_camera”处的错误。”

关于Camera这块我的xaml是:

 

ContractedBlock.gifExpandedBlockStart.gifCode
 <PerspectiveCamera Position="0 0 2" x:Name="_camera" LookDirection="0 0 -1" FieldOfView="120" UpDirection="0,1,0">
                    
<PerspectiveCamera.Transform>
                        
<Transform3DGroup>        
                            
                            
<RotateTransform3D CenterX="{Binding ElementName=_camera, Path=Position.X}"
                                               CenterY
="{Binding ElementName=_camera, Path=Position.Y}"
                                               CenterZ
="{Binding ElementName=_camera, Path=Position.Z}">
                                
<RotateTransform3D.Rotation>
                                    
<AxisAngleRotation3D x:Name="_rotateX" Axis="1 0 0"></AxisAngleRotation3D>
                                
</RotateTransform3D.Rotation>
                            
</RotateTransform3D>

 

根据异常的提示,我猜想是为了提高效率,XamlReader在创建Camera之后即将其Freeze了,因此不能再对其做更改。或者说,认为XamlReader的动作是一种“静态”的初始化操作,由于指定了ElementName,因此在初始化时直接去用_camera来作为绑定源进行绑定。

好吧,那我就换种方式:

 

ContractedBlock.gifExpandedBlockStart.gifCode
   <RotateTransform3D CenterX="{Binding RelativeSource={RelativeSource AncestorType={x:Type PerspectiveCamera}}, Path=Position.X}"
                                               CenterY
="{Binding RelativeSource={RelativeSource AncestorType={x:Type PerspectiveCamera}}, Path=Position.Y}"
                                               CenterZ
="{Binding RelativeSource={RelativeSource AncestorType={x:Type PerspectiveCamera}}, Path=Position.Z}">
                                
<RotateTransform3D.Rotation>
                                    
<AxisAngleRotation3D x:Name="_rotateX" Axis="1 0 0"></AxisAngleRotation3D>                                     
                                
</RotateTransform3D.Rotation>
                            
</RotateTransform3D>

 

其实本质上还是绑定到_camera,但是这次的绑定是延迟确立的,因此不会报错。

PS:原来的代码是在.Net3.5 beta版下做的,现在是.Net3.5 SP1

转载于:https://www.cnblogs.com/RMay/archive/2008/12/10/1352156.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值