2014-09-12 69 views
0

我試圖很好地使用ReactiveList,並且我認爲我很接近。ReactiveList不在GUI中更新

我的期望是,只有「豐田」被用戶按下濾波器按鈕

XAML(是的,快速Ñ髒,對於過濾器沒有命令)之後顯示

<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

你的bug在IsVisible的setter中。通過預先分配_isVisible的值,RaiseAndSetIfChanged總是認爲該值從未改變過。刪除_isVisible = value;和一切應該工作。哈哈!

+0

哈!當然。當發現一個框架常識似乎被禁用。保羅。時間耦合在開始時總是很棘手 – buckley 2014-09-13 07:16:12

+0

沒有時間耦合... RaiseAndSet做2件事:) – buckley 2014-09-15 07:55:55