我刚刚开始研究 ReactiveUI,我想我错过了一些东西。假设我有一个“连接”按钮,并想根据文本框中的服务器地址创建一个新的网络连接。我想,我会创建一个 ReactiveCommand 并将其绑定到 Button,然后使用服务器地址属性的值执行类似 WithLatestFrom 的操作(这就是我在 Java 或 Typescript 中完成的方式)。
但是我找不到正确的语法。谁能详细说明?BR,丹尼尔
问问题
83 次
2 回答
2
好的,我的朋友,如果我理解你应该这样做:
首先你的 ViewModel,你想从 ReactiveObject 派生以便访问this.RaiseAndSetIfChanged(...) wichs triggers INotifyPropertyChanged
public class MainViewModel : ReactiveObject
{
private string _connectionUrl;
public string ConnectionUrl
{
get => _connectionUrl;
set => this.RaiseAndSetIfChanged(ref _connectionUrl, value);
}
public ReactiveCommand ConnectCommand { get; set; }
public MainViewModel()
{
ConnectCommand = ReactiveCommand.Create(() =>
{
//your logic goes here...
System.Diagnostics.Debug.WriteLine("Button Pressed");
System.Diagnostics.Debug.WriteLine($"{ConnectionUrl}");
});
}
}
接下来要做的是通过视图的DataContext连接你的视图和你的视图模型
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
当然还有将控件绑定到属性和命令所需的 XAML
<Window x:Class="WPFRx.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBox x:Name="Connection"
Text="{Binding ConnectionUrl, Mode=TwoWay}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Width="200"/>
<Button x:Name="BtnConnect"
Content="Connect"
Command="{Binding ConnectCommand}"/>
</StackPanel>
</Window>
我希望这对你有帮助,问候。
于 2018-03-13T04:45:20.850 回答
1
阿德里安的回答很好,我会添加一些代码来帮助更多:
public class MainViewModel : ReactiveObject
{
private string connectionUrl;
// constructor
public MainViewModel()
{
// maybe you need to disable the button if the textbox is empty
// ypu can create an observable to check if ConnectionUrl is null or empty
var canConnect = this.WhenAnyValue(x => x.ConnectionUrl)
.Where(conn => !string.IsNullOrEmpty(conn);
// use "ReactiveCommand.CreateFromTask" if you need asynchronous operations.
ConnectCommand = ReactiveCommand.Create(() =>
{
// you can use the ConnectionUrl property here, for example
var dbConnection = new DbConnection(ConnectionUrl);
}, canConnect); // <-- we are telling to the command when will be enabled
}
// this property will be binded to the textbox
public string ConnectionUrl
{
get => connectionUrl;
set => this.RaiseAndSetIfChanged(ref connectionUrl, value);
}
// this command will be binded to the button
public ReactiveCommand ConnectCommand { get; }
}
于 2018-05-13T15:36:58.170 回答