我有两个建议:
如果您正在使用f#交互式,请检查您是否已安装WFP事件循环。F#交互式默认设置了一个WinForms事件循环,WinForms和WFP事件循环之间存在一些兼容性,但不是所有东西都可以正常工作。要安装事件循环,请使用以下脚本:
#light
// When running inside fsi, this will install a WPF event loop
#if INTERACTIVE
#I "c:/Program Files/Reference Assemblies/Microsoft/Framework/v3.0";;
#I "C:/WINDOWS/Microsoft.NET/Framework/v3.0/WPF/";;
#r "presentationcore.dll";;
#r "presentationframework.dll";;
#r "WindowsBase.dll";;
module WPFEventLoop =
open System
open System.Windows
open System.Windows.Threading
open Microsoft.FSharp.Compiler.Interactive
open Microsoft.FSharp.Compiler.Interactive.Settings
type RunDelegate< b> = delegate of unit -> b
let Create() =
let app =
try
// Ensure the current application exists. This may fail, if it already does.
let app = new Application() in
// Create a dummy window to act as the main window for the application.
// Because we re in FSI we never want to clean this up.
new Window() |> ignore;
app
with :? InvalidOperationException -> Application.Current
let disp = app.Dispatcher
let restart = ref false
{ new IEventLoop with
member x.Run() =
app.Run() |> ignore
!restart
member x.Invoke(f) =
try disp.Invoke(DispatcherPriority.Send,new RunDelegate<_>(fun () -> box(f ()))) |> unbox
with e -> eprintf "
ERROR: %O
" e; rethrow()
member x.ScheduleRestart() = ()
//restart := true;
//app.Shutdown()
}
let Install() = fsi.EventLoop <- Create()
WPFEventLoop.Install();;
#endif
我没有进行过太多测试,但我认为使用动画故事板会比使用计时器得到更加平滑和一致的结果。我认为这会像这样(改变宽度属性,我还没想出如何改变位置):
#light
open System
open System.Windows
open System.Windows.Controls
open System.Windows.Shapes
open System.Windows.Media
open System.Windows.Media.Animation
let rect = new Rectangle(Fill = new SolidColorBrush(Colors.Red), Height = 20., Width = 20., Name = "myRectangle")
let canvas =
let c = new Canvas()
c.Children.Add(rect) |> ignore
c
NameScope.SetNameScope(canvas, new NameScope());
canvas.RegisterName(rect.Name, rect)
let window = new Window(Content = canvas)
let nfloat f = new Nullable<float>(f)
let myDoubleAnimation = new DoubleAnimation(From = nfloat 20.0, To = nfloat 50.0,
Duration = new Duration(TimeSpan.FromSeconds(5.)),
RepeatBehavior = RepeatBehavior.Forever)
let myStoryboard =
let sb = new Storyboard()
sb.Children.Add(myDoubleAnimation)
sb
Storyboard.SetTargetName(myDoubleAnimation, rect.Name);
Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Rectangle.WidthProperty))
rect.Loaded.Add(fun _ -> myStoryboard.Begin canvas)
let main() =
let app = new Application()
app.Run window |> ignore
[<STAThread>]
do main()