Notes/Notes.UI/Views/NoteView.axaml.cs

34 lines
1.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Notes.Models;
using Notes.ViewModels;
namespace Notes.Views;
public class NoteView : TemplatedControl
{
//TemplatedControl必须在这监听比较晚创建但是实例化是一开始执行的会找不到子元素
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
var listBox = e.NameScope.Find<ListBox>("listNotes");
if (listBox == null) throw new NullReferenceException(nameof(listBox));
listBox.AddHandler(SelectingItemsControl.SelectionChangedEvent, this.Handler);
}
private void Handler(object? sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count>0)
{
var eAddedItem = e.AddedItems[0];
if (eAddedItem is Note note)
{
if (DataContext is NoteViewModel noteViewModel)
{
noteViewModel.SelectedNote = note;
}
}
}
}
}