Created
August 10, 2020 09:42
-
-
Save grokys/722d90147f8b3a6632d5b1bcb362e074 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
this.InitializeComponent(); | |
this.AttachDevTools(); | |
DataContext = new ViewModel(); | |
var btn = this.FindControl<Button>("doit"); | |
btn.Click += (s, e) => ((ViewModel)DataContext).Foo(); | |
} | |
private void InitializeComponent() | |
{ | |
AvaloniaXamlLoader.Load(this); | |
} | |
} | |
public enum MyEnum | |
{ | |
One, | |
Two, | |
} | |
public class ViewModel : ReactiveObject | |
{ | |
public ViewModel() | |
{ | |
Objects = new ObservableCollection<TestModel> | |
{ | |
new TestModel(new MyObj { Value = MyEnum.One }), | |
new TestModel(new MyObj { Value = MyEnum.Two }), | |
}; | |
SelectedObject = Objects[0]; | |
} | |
public ObservableCollection<TestModel> Objects { get; } | |
TestModel _selectedObject; | |
public TestModel SelectedObject | |
{ | |
get => _selectedObject; | |
set => this.RaiseAndSetIfChanged(ref _selectedObject, value); | |
} | |
public void Foo() | |
{ | |
foreach (TestModel obj in Objects) | |
{ | |
obj.Dispose(); | |
} | |
SelectedObject = null; | |
Objects.Clear(); | |
} | |
} | |
public class MyObj | |
{ | |
public MyEnum Value { get; set; } | |
} | |
public sealed class TestModel : INotifyPropertyChanged, IDisposable | |
{ | |
private void OnPropertyChanged(string property) | |
{ | |
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
public MyEnum Value | |
{ | |
get => Obj.Value; | |
set | |
{ | |
if (value != Obj.Value) // Crash happens here because Obj is null | |
{ | |
Obj.Value = value; | |
OnPropertyChanged(nameof(Value)); | |
} | |
} | |
} | |
public static IEnumerable<MyEnum> SelectableValues { get; } = new[] { MyEnum.One, MyEnum.Two }; | |
internal MyObj Obj; | |
internal TestModel(MyObj obj) | |
{ | |
Obj = obj; | |
} | |
public void Dispose() | |
{ | |
Obj = null; | |
PropertyChanged = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment