ReactiveList不会在GUI中更新

时间:2014-09-12 15:59:04

标签: reactiveui

我试图充分利用ReactiveList,我想我已经接近了。

我的期望是只有"丰田"用户按下过滤器按钮后显示

XAML(是的,快速n脏,没有过滤器命令)

<Window
    x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"
    Height="350"
    Width="525">
    <StackPanel>
        <ComboBox
            ItemsSource="{Binding Path=CarsVM}"
            DisplayMemberPath="Name" />

        <Button
            Click="ButtonBase_OnClick">
            Filter
        </Button>

    </StackPanel>
</Window>

代码

using System.Windows;
using ReactiveUI;

namespace WpfApplication1
{

    public partial class MainWindow
    {
        private readonly ViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();

            _viewModel = new ViewModel();
            DataContext = _viewModel;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            _viewModel.ChangeFilter();
        }
    }
}

public class CarViewModel : ReactiveObject
{
    private bool _isVisible = true;

    public CarViewModel(string name)
    {
        Name = name;
    }

    public bool IsVisible
    {
        get { return _isVisible; }
        set
        {
            _isVisible = value;
            this.RaiseAndSetIfChanged(ref _isVisible, value);
        }
    }

    public string Name { get; set; }
}

public class ViewModel
{
    private readonly ReactiveList<CarViewModel> _cars = new ReactiveList<CarViewModel>
    {
        new CarViewModel("bmw"),
        new CarViewModel("toyota"),
        new CarViewModel("opel")
    };


    public ViewModel()
    {
        _cars.ChangeTrackingEnabled = true;

        CarsVM = _cars.CreateDerivedCollection(x => x, x => x.IsVisible);
    }

    public IReactiveDerivedList<CarViewModel> CarsVM { get; set; }

    public void ChangeFilter()
    {
        foreach (var car in _cars)
        {
            car.IsVisible = car.Name.Contains("y");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的错误在IsVisible的设置器中。通过预先指定_isVisible的值,RaiseAndSetIfChanged始终认为该值从未改变过。删除_isVisible = value;,一切都应该有效。