05.06.2024 14:49 Gtk3
Приклад використання віджету ListBox

dotnet new consoledotnet add package GtkSharpdotnet runusing Gtk;
class Program
{
public static void Main()
{
Application.Init();
new FirstWindow();
Application.Run();
}
public static void Quit()
{
Application.Quit();
}
}using Gtk;
class FirstWindow : Window
{
ListBox listBox = new ListBox() { SelectionMode = SelectionMode.Single };
ScrolledWindow scroll;
public FirstWindow() : base("Test")
{
SetDefaultSize(600, 350);
SetPosition(WindowPosition.Center);
DeleteEvent += delegate { Program.Quit(); };
VBox vBox = new VBox();
Add(vBox);
listBox.ButtonPressEvent += OnListBoxButtonPress;
//Button
{
HBox hBox = new HBox();
vBox.PackStart(hBox, false, false, 5);
Button buttonAdd = new Button("Додати");
buttonAdd.Clicked += OnAddClick;
hBox.PackStart(buttonAdd, false, false, 5);
Button buttonClear = new Button("Очистити");
buttonClear.Clicked += OnClearClick;
hBox.PackStart(buttonClear, false, false, 5);
}
//ListBox
{
HBox hBox = new HBox();
vBox.PackStart(hBox, false, false, 5);
scroll = new ScrolledWindow() { ShadowType = ShadowType.In, HeightRequest = 300, WidthRequest = 600 };
scroll.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);
scroll.Add(listBox);
hBox.PackStart(scroll, false, false, 5);
}
ShowAll();
}
void OnAddClick(object? sender, EventArgs args)
{
ListBoxRow row = [new Label($"{DateTime.Now.ToString("HH:mm:ss")} - text") { Halign = Align.Start }];
listBox.Add(row);
listBox.SelectRow(row);
listBox.ShowAll();
scroll.Vadjustment.Value = scroll.Vadjustment.Upper;
}
void OnClearClick(object? sender, EventArgs args)
{
foreach (Widget item in listBox.Children)
listBox.Remove(item);
}
void OnListBoxButtonPress(object? sender, ButtonPressEventArgs args)
{
if (args.Event.Type == Gdk.EventType.DoubleButtonPress)
{
ListBoxRow[] selectedRows = listBox.SelectedRows;
if (selectedRows.Length != 0)
Console.WriteLine(((Label)selectedRows[0].Child).Text);
}
}
}© accounting.org.ua - 2025