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

ReactiveUI - Should I use {Binding } or this.Bind(...)?

使用 ReactiveUI 时,可以在 xaml ...

中设置绑定
<TextBox x:Name="SomeProperty" Text="{Binding SomeProperty}" />

或在代码后面

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

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

例如

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

我使用 {Binding } 是不是错了,或者我可以混合搭配 .xamlcode behind 吗?!

不,你使用 Binding 没有错....如果你想 'Master' WPF\XAML 然后坚持使用 MVVM 模式(绑定),我的意思是坚持下去....如果你 'mix and match .xaml and code behind' 你最终会得到无法维护、难以管理的意大利面条代码....

听起来您已经掌握了 'Binding',您的挑战应该是编写一个 WPF 应用程序,除了由 Visual Studio 创建的内容外绝对没有代码隐藏...

就个人而言,我拒绝在不遵循 MVVM 模式的 WPF 应用程序上工作,它告诉我原来的开发人员并不关心编写另一个开发人员(甚至他们自己)可以工作的代码......

您可能会发现此 link 有用...

https://rachel53461.wordpress.com/category/mvvm/

艾诺伊

放置在 Window\UserControl *.cs 文件中的任何代码都可能破坏 MVVM 模式,自定义控件可能例外,您可以在其中使用 Dependencyproperties 在 属性 编辑器中公开属性(在设计时-时间)...

例如,您应该使用实现 ICommand 而不是事件处理程序的 RelayCommand(或 DelegateCommand)。也就是说,永远不要简单地双击一个按钮在一个Window(不是MVVM)的*.cs文件中创建事件存根,在ViewModel中创建一个Command,它应该是一个单独的文件(不是继承自 Window 的 Window.cs 文件,因为继承了 UserControl 的 UserControl 是错误的)。您的 ViewModel 需要实现 InotifyPropertyChanged 或继承一个实现了 InotifyPropertyChanged 的​​ ViewModelBase,那么您应该使用按钮的 Command 和 CommandParameter 进行绑定,并将 call\pass 个对象返回到 ViewModel,即 MVVM

您可能会发现这很有用...

http://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/

我认为您可能(几乎)不用 XAML 绑定就可以逃脱,但要付出编写更多代码的额外代价。我将以 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。

接下来,您为 TileViewModelsimilar to this one from Evolve example.

创建一个简单的视图

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

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

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

希望对您有所帮助!