【问题标题】:ReactiveUI and casting in WhenAnyReactiveUI 和WhenAny 中的强制转换
【发布时间】:2013-08-11 00:24:46
【问题描述】:

我正在做的是这样的:

Item.PropertyChanged += (sender, args) =>
{
    if(sender is IInterface)
        DoSomethingWith(((IInterface)sender).PropertyFromInterface);
}

我将如何在 RxUI 中实现这样的流?

我试过了:

this.WhenAny(x => (x.Item as IInterface).PropertyFromInterface, x.GetValue())
    .Subscribe(DoSomethingWith);

但似乎不可能做到。

我必须做这样的财产吗? ->

private IInterface ItemAsInterface { get { return Item as IInterface; } }

我现在做了一个这样的解决方法:

this.WhenAny(x => x.Item, x => x.GetValue()).OfType<IInterface>()
    .Select(x => x.PropertyFromInterface).DistinctUntilChanged()
    .Subscribe(DoSomethingWith);

但我真正想要的是在 Item 属于 IInterface 时获取“PropertyFromInterface”的 propertychanged 更新。

【问题讨论】:

    标签: c# reactiveui


    【解决方案1】:

    怎么样:

    this.WhenAny(x => x.Item, x => x.Value as IInterface)
        .Where(x => x != null)
        .Subscribe(DoSomethingWith);
    

    更新:好的,我隐约明白你现在想做什么——我会这样做:

    public ViewModelBase()
    {
        // Once the object is set up, initialize it if it's an IInterface
        RxApp.MainThreadScheduler.Schedule(() => {
            var someInterface = this as IInterface;
            if (someInterface == null) return;
    
            DoSomethingWith(someInterface.PropertyFromInterface);
        });
    }
    

    如果你真的想通过 PropertyChanged 来初始化它:

    this.Changed
        .Select(x => x.Sender as IInterface)
        .Where(x => x != null)
        .Take(1)   // Unsubs automatically once we've done a thing
        .Subscribe(x => DoSomethingWith(x.PropertyFromInterface));
    

    【讨论】:

    • 我想绑定到接口上定义的属性,而不是对象本身。这将在 Item 本身被替换时抛出,而不是在它的属性被更改时抛出。向 OP 添加一些内容以进行澄清。
    • 实际上想做什么?我不知道你为什么想要这样的构造
    • 我有一个以视图模型库为项目的导体视图模型。如果项目当前属于某个接口,则应该观察它当时具有的某个属性。之前,我在项目上注册/取消注册属性更改(无论何时被替换)并询问它是否属于接口。我希望我可以放弃注册/注销并编写一个可以自行完成工作的可观察对象。
    【解决方案2】:

    查看我的旧问题,我正在寻找类似这样的解决方案:

    this.WhenAny(x => x.Item, x => x.GetValue()).OfType<IInterface>()
        .Select(x => x.WhenAny(y => y.PropertyFromInterface, y => y.Value).Switch()
        .Subscribe(DoSomethingWith);
    

    对我来说缺少的链接是 .Switch 方法。

    此外,如果属性不是所需的类型,我希望 observable 不做任何事情:

    this.WhenAny(x => x.Item, x => x.Value as IInterface)
        .Select(x => x == null ? 
                   Observable.Empty : 
                   x.WhenAny(y => y.PropertyFromInterface, y => y.Value)
        .Switch().Subscribe(DoSomethingWith);
    

    (例如,当我将this.Item 设置为IInterface 的实例时,我希望DoSomethingWith 监听该实例的PropertyFromInterface 的更改,并且当this.Item 设置为不同的值时,observable 不应该继续触发直到this.Item 再次成为IInterface 的实例。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 2010-12-08
      • 2012-02-10
      • 2021-01-24
      • 2015-02-15
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多