tags:

views:

60

answers:

2

Let's say I have this xaml code :

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <Canvas>
        <Rectangle Name="papan" Fill="Red" Height="20" Width="20" />
    </Canvas>
</Window>

And I have a file named Program.fs (F# code), how can I access "papan", for example, from my code?

Thanks

+1  A: 

Something like this?

open System.Windows
open System.Windows.Markup
open System.Windows.Shapes

let xaml = @"<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'&gt;
    <Canvas>
        <Rectangle Name='papan' Fill='Red' Height='20' Width='20' />
    </Canvas>
</Window>"

let wnd = XamlReader.Parse(xaml) :?> Window
let rect = wnd.FindName("papan") :?> Rectangle

If the XAML is in a separate file, you can use XamlReader.Load instead of XamlReader.Parse.

kvb
thank you. your answer is very helpful since I am new with WPF.
+3  A: 

In addition to the answer posted by kvb, you can use F# dynamic invoke operator (which is similar to dynamic in C# 4.0) to get a nicer syntax. The operator allows you to define the meaning of expressions such as wnd?papan. You can for example specify that this should perform the lookup using FindName method. The operator definition looks like this:

let (?) (this : Control) (prop : string) : 'T = // '
  this.FindName(prop) :?> 'T

Then you can just write:

let rect : Rectangle = wnd?papan 

You still need to write the type (Rectangle) explicitly, so that F# type inference can use it, but the syntax is a bit more comfortable.

Tomas Petricek