如何在类的setter之外更改属性时使ReactiveUI WhenAnyValue发出

时间:2019-06-18 21:37:02

标签: reactiveui rx.net

我想知道如何仍然可以使用可以在类中的属性设置器之外更改的属性来触发ReactiveUI的WhenAnyValue。请原谅这个例子,只是试图使事情变得更清楚。可以说我有两个类,一个是人,另一个是地址。

public class Address : ReactiveObject
{
    [Reactive]
    public string Street1 { get; set; }
    [Reactive]
    public string Street2 { get; set; }
    [Reactive]
    public string State { get; set; }
    [Reactive]
    public string City { get; set; }
    [Reactive]
    public string ZipCode { get; set; }
}

public class Person : ReactiveObject
{

    [Reactive]
    public string Name { get; set; }

    [Reactive]
    public Address Address { get; set; }


    public Person(Address address)
    {
        Address = address;
        address.Changed .Subscribe(_ =>
        {
            //Tried this way
            this.RaisePropertyChanged(_.PropertyName);

            //Also tried this way
            this.RaisePropertyChanged(nameof(Address));
        });

        this.Changed.Subscribe(_ =>
        {
            Console.WriteLine($"Person Property: {_.PropertyName} changed");
        });

        this.WhenAnyValue(_ => _.Name, _ => _.Address, (a, b) => "Emit").Subscribe(Console.WriteLine);
    }
}

private static void Main(string[] args)
{
    var address = new Address
    {
        Street1 = "Street1",
        Street2 = "Street2",
        City = "City",
        State = "LA",
        ZipCode = "11111"
    };

    var person = new Person(address);

    person.Name = "Name";
    Task.Delay(3000).Wait();

    address.City = "CityChanged";


    Console.ReadLine();
}

我想我只需要订阅Address Changed Observable,然后从Person RaisePropertyChanged中获取Address属性。它确实会向Person的Changed Observable发出,并且行为符合我的预期,但是Person内的WhenAnyValue Observable不会在这种情况下发出。

1 个答案:

答案 0 :(得分:0)

我发现了问题。问题是我必须将所有嵌套属性添加到WhenAnyValue。在我的示例中,如果我更改此行

this.WhenAnyValue(_ => _.Name, _ => _.Address, (a, b) => "Emit").Subscribe(Console.WriteLine);

this.WhenAnyValue(_ => _.Name, _ => _.Address.City, (a, b) => "Emit").Subscribe(Console.WriteLine);

它发出。那里的关键是将其从_.Address更改为_.Address.City。此外,它仍然可以发射而无需订阅Address.Changed Observable,这甚至更好。