【问题标题】:Zip does not behave as expectedZip 的行为不符合预期
【发布时间】:2018-03-16 14:21:59
【问题描述】:

在我的最新项目中,我决定测试响应式编程世界提供的一些功能。 由于它是一个 C# 项目,我已经开始使用 System.Reactive 和 ReactiveProperty nuget 包。 在我的项目中,我尝试通过以下代码组合绑定到 WPF 文本框控件的 2 个属性:

    public ReactiveProperty<string> InputFieldFirst { get; set; }
    public ReactiveProperty<string> InputFieldSecond { get; set; }
    public ReactiveProperty<string> RxTest { get; set; }

    public MainViewModel()
    {

        InputFieldFirst = new ReactiveProperty<string>("Demo");
        InputFieldSecond = new ReactiveProperty<string>("Test");
        RxTest = InputFieldFirst.Zip(InputFieldSecond, CombineStrings).Delay(TimeSpan.FromMilliseconds(500)).ToReactiveProperty();

    }

    private string CombineStrings(string a, string b)
    {
        return $"{a} {b}";
    }

绑定到 RxTest 的文本框获取“演示测试”的初始值 - 但是当我编辑绑定到 InputFieldFirst 或 InputFieldSecond 的文本框的内容时,不会触发更新。

当我如下更改代码时,对 InputFieldFirst 的所有更新都是可见的,在 RxTest 中按预期延迟。

    public MainViewModel(IReactiveRepository<DemoContent> repo)
    {
        InputFieldFirst = new ReactiveProperty<string>("Demo");
        InputFieldSecond = new ReactiveProperty<string>("Test");
        RxTest = InputFieldFirst.Delay(TimeSpan.FromMilliseconds(500)).ToReactiveProperty();
    }

任何提示如何设置 .Zip() 都会非常好。

完成更新

文本框的 XAML 代码

    <Grid>
        <StackPanel>
            <TextBox Text="{Binding InputFieldFirst.Value, UpdateSourceTrigger=PropertyChanged}"></TextBox>
            <TextBox Text="{Binding InputFieldSecond.Value, UpdateSourceTrigger=PropertyChanged}"></TextBox>
            <TextBox Text="{Binding RxTest.Value}"></TextBox>
        </StackPanel>
    </Grid>

【问题讨论】:

    标签: c# wpf rx.net reactive-property


    【解决方案1】:

    我认为您想使用CombineLatest 而不是ZipZip 像拉链一样工作:将 Stream1 的第 n 条消息与 Stream2 的第 n 条消息匹配。

    例子:

    Stream1: A----B-----C----D--E-
    Stream2: 1-2-3----4---5-6--7--
    Zip    : A1---B2----C3---D4-E5
    

    数字输出更快并不重要:Zip 始终将第一个数字与第一个字母匹配,将第二个数字与第二个字母匹配,等等。

    【讨论】:

    • 谢谢。我没有理解“成对时尚”描述的含义。在这个例子中,CombineLatest 就像一个魅力
    • 对于 WPF,请记住在绑定上将更改触发器设置为 PropertyChange。也许不适合@maltmann,但其他人可能需要这个
    猜你喜欢
    • 2017-01-27
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2021-04-09
    相关资源
    最近更新 更多