gpt4 book ai didi

wpf - 将 WPF 的控件绑定(bind)到 F# 选项

转载 作者:行者123 更新时间:2023-12-04 22:32:23 27 4
gpt4 key购买 nike

假设我有一个业务对象(没有 AllowNullLiteralAttribute )。

type Person(name: string) =
member val Name = name
override x.ToString() = name

还有一个 View 模型,可选择设置所选人员。
type MainWindowModel() =

let mutable selectedPerson: Person option = None
:
member val People = ObservableCollection<Person>()
member x.SelectedPerson
with get() = selectedPerson
and set(v) =
if selectedPerson <> v then
selectedPerson <- v
x.RaisePropertyChanged("SelectedPerson")

绑定(bind) WPF 控件的 SelectedItem 的最佳方法是什么?属性到 F# 选项属性(不使用 AllowNullLiteralAttribute )?

如果我这样做...

<StackPanel>
<ListBox ItemsSource="{Binding People}"
SelectedItem="{Binding SelectedPerson}"
DisplayMemberPath="Name" />
<TextBlock Text="{Binding SelectedPerson}" />
</StackPanel>

...导致错误,无法将“George”从“Person”类型转换为“Microsoft.FSharp.Core.FSharpOption`1[Person]”类型

最佳答案

我目前采取的方法是自己写IValueConverter .

open System
open System.Globalization
open System.Windows.Data

type OptionsTypeConverter() =

// from http://stackoverflow.com/questions/6289761
let (|SomeObj|_|) =
let ty = typedefof<option<_>>
fun (a:obj) ->
let aty = a.GetType()
let v = aty.GetProperty("Value")
if aty.IsGenericType && aty.GetGenericTypeDefinition() = ty then
if a = null then None
else Some(v.GetValue(a, [| |]))
else None

interface IValueConverter with

member x.Convert(value: obj, targetType: Type, parameter: obj, culture: CultureInfo) =
match value with
| null -> null
| SomeObj(v) -> v
| _ -> value

member x.ConvertBack(value: obj, targetType: Type, parameter: obj, culture: CultureInfo) =
match value with
| null -> None :> obj
| x -> Activator.CreateInstance(targetType, [| x |])

然后我的 XAML 看起来像这样:

<StackPanel>
<ListBox ItemsSource="{Binding People}"
SelectedItem="{Binding SelectedPerson, Converter={StaticResource OptionsTypeConverter1}}"
DisplayMemberPath="Name" />
<TextBlock Text="{Binding SelectedPerson, Converter={StaticResource OptionsTypeConverter1}}" />
</StackPanel>

可能有更简单的方法。该转换器可能已经存在于框架中。那里可能有更好的实现。

关于wpf - 将 WPF 的控件绑定(bind)到 F# 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com