TextBoxTest.axaml代码
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="325" Width="390" x:Class="AvaloniaUI.TextBoxTest" Title="TextBoxTest"> <Grid Margin="5" RowDefinitions="2*,*"> <TextBox Name="txt" TextWrapping="Wrap" AcceptsReturn="True"> The Ministry of Truth contained, it was said, three thousand rooms above ground level, and corresponding ramifications below. Scattered about London there were just three other buildings of similar appearance and size. So completely did they dwarf the surrounding architecture that from the roof of Victory Mansions you could see all four of them simultaneously. They were the homes of the four Ministries between which the entire apparatus of government was divided. The Ministry of Truth, which concerned itself with news, entertainment, education, and the fine arts. The Ministry of Peace, which concerned itself with war. The Ministry of Love, which maintained law and order. And the Ministry of Plenty, which was responsible for economic affairs. Their names, in Newspeak: Minitrue, Minipax, Miniluv, and Miniplenty. </TextBox> <ScrollViewer Foreground="Blue" Grid.Row="1" Margin="0,10,0,5" VerticalScrollBarVisibility="Auto"> <StackPanel> <TextBlock>Current selection: </TextBlock> <TextBlock Name="txtSelection" TextWrapping="Wrap"></TextBlock> </StackPanel> </ScrollViewer> </Grid> </Window>
TextBoxTest.axaml.cs代码
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using System;
namespace AvaloniaUI;
public partial class TextBoxTest : Window
{
public TextBoxTest()
{
InitializeComponent();
txt.PropertyChanged += (sender, e) =>
{
if (e.Property == TextBox.SelectionStartProperty || e.Property == TextBox.SelectionEndProperty)
{
txt_SelectionChanged(sender, txt.SelectionStart, txt.SelectionEnd);
}
};
}
private void txt_SelectionChanged(object? sender, int start, int end)
{
if (txtSelection == null || txt.Text == null)
return;
int selStart = Math.Min(start, end);
int selEnd = Math.Max(start, end);
int length = selEnd - selStart;
if (selStart >= 0 && selStart + length <= txt.Text.Length)
{
txtSelection.Text = $"Selection from {selStart} to {selEnd}, {(length == 0 ? "no text" : txt.Text.Substring(selStart, length))}";
}
}
}
运行效果

浙公网安备 33010602011771号