gpt4 book ai didi

c# - ReactiveUI - 我应该使用 {Binding } 还是 this.Bind(...)?

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:14 25 4
gpt4 key购买 nike

当使用 ReactiveUI 时,可以在 xaml 中设置绑定(bind) ...

<TextBox x:Name="SomeProperty" Text="{Binding SomeProperty}" />

或在代码后面

this.Bind(ViewModel, vm.SomeProperty, v => v.SomeProperty.Text);

似乎在某些情况下(例如绑定(bind)到 ListBox 中的子对象)使用 .xaml 选项似乎是唯一的方法

例如

<ListView>
<ListView.ItemTemplate>
<DataTemplate DataType="ListViewItem">
<TextBox Text="{Binding ChildViewModelProperty}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

我使用 {Binding } 是不是错了,或者我可以按照我认为合适的方式混合和匹配 .xamlcode behind ?!

最佳答案

我认为您可能(几乎)不使用 XAML 绑定(bind)而逃脱,但要付出额外的代价来编写更多代码。我将使用 Anaïs Betts 的 XamarinEvolve2014 demo举个例子。

首先,您需要为列表中的项目定义一个 ViewModel(类似于 LoginTeamTileViewModel ):

public class TileViewModel : ReactiveObject
{
string name;
public string Name {
get { return name; }
set { this.RaiseAndSetIfChanged(ref name, value); }
}
}

然后,您需要在您的 ViewModel 中公开这些类的集合 - for example as a ReactiveList :

public class ViewModel : ReactiveObject
{
public ReactiveList<TileViewModel> Tiles { get; private set; }
}

您可以使用 ReactiveDerivedCollection 从您的模型中创建这些 ViewModel。

接下来,您为 TileViewModel 创建一个简单的 View ,similar to this one from Evolve example .

最后,您应该在 ListView 中使用创建的 View 作为数据模板,like in the example .请注意,它仍然使用 {Binding},但仅用于 ViewModel 属性,而不用于单独的字段,这看起来更清晰。 (遗憾的是,我有一段时间没有编写任何 WPF,所以我无法在这里快速编写任何示例 - 欢迎编辑!)。

在后面的代码中,您应该将集合绑定(bind)到 ListView 的 ItemsSourcelike here :

this.OneWayBind(ViewModel, vm => vm.Tiles, v => v.ListView.ItemsSource);

希望这对您有所帮助!

关于c# - ReactiveUI - 我应该使用 {Binding } 还是 this.Bind(...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571417/

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