代码之家  ›  专栏  ›  技术社区  ›  buckley

ReactiveList在GUI中不更新

  •  0
  • buckley  · 技术社区  · 10 年前

    我正在努力充分利用ReactiveList,我想我已经接近了。

    我的期望是,用户按下过滤器按钮后只显示“丰田”

    XAML(yes,quick n dirty,无筛选器命令)

    <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 回复  |  直到 10 年前
        1
  •  1
  •   Ana Betts    10 年前

    您的bug位于IsVisible的setter中。通过预先分配_isVisible的值, RaiseAndSetIfChanged 总是认为价值从未改变。去除 _isVisible = value; 一切都应该正常。