Как сделать ToolBar
Прочел в документации, что есть такая штука как ToolBar. Я хочу попробовать заменить ImageButton удаления и редактирования в статьях:
на вот такой вид:
И такой вопрос, его можно сделать только наверху экрана как на примере 2 рисунка или можно впихнуть в Border, чтобы они были на каждой статье как ImageButton на 1 рисунке. Буду рад если покажете статью с решением или видео, так как в интернете я не нашел ответа. Сразу уточню, я не использую MVVM подход в приложении.
Вот частички кода, если нужны:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="IbragimovLinux.Windows.InstallationWindow"
xmlns:entities="clr-namespace:IbragimovLinux.Entities"
Title="Установка"
BackgroundColor="LightGrey">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<!-- Кнопки "Выйти" и "Добавить" -->
<RowDefinition Height="Auto"/>
<!-- Заголовок таблицы -->
<RowDefinition Height="*"/>
<!-- Список данных -->
</Grid.RowDefinitions>
<!--<HorizontalStackLayout Grid.Row="0" Spacing="10" Padding="10">
<SearchBar
x:Name="SearchBar"
Placeholder="Search articles..."
WidthRequest="250"
HorizontalOptions="StartAndExpand"/>-->
<HorizontalStackLayout
Grid.Row="1"
Padding="10"
HorizontalOptions="End">
<ImageButton
x:Name="AddButton"
Source="addbutton.png"
WidthRequest="30"
HeightRequest="30"
Clicked="AddButton_Clicked"
IsVisible="{Binding ShowAdminButtons}"/>
</HorizontalStackLayout>
<!-- RefreshView для обновления списка -->
<RefreshView
Grid.Row="2"
x:Name="RefreshLV"
Refreshing="RefreshData">
<ScrollView>
<CollectionView x:Name="InstallationLV">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="{x:Type entities:Installation}">
<Border
StrokeThickness="0.5"
Stroke="Black"
Padding="10,15">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.RowSpan="3"
Source="D:\Ibra\IbragimovLinux\IbragimovLinux\Resources\Images\dotnetbot.png"
WidthRequest="60"
HeightRequest="60"
Aspect="AspectFill"/>
<Label
Grid.Column="1"
Grid.Row="0"
Text="{Binding Title}"
MaxLines="1"
LineBreakMode="TailTruncation"
FontSize="18"
FontAttributes="Bold"
TextColor="Black"/>
<Label
Grid.Column="1" Grid.Row="1"
FontSize="14"
TextColor="Blue"
Text="{Binding Create_dt}"/>
<Label
Grid.Column="1"
Grid.Row="2"
FontSize="16"
TextColor="#333333"
Text="{Binding Description, StringFormat='Описание: {0}'}"
LineBreakMode="TailTruncation"
MaxLines="3"/>
<HorizontalStackLayout Grid.Column="2" Grid.RowSpan="3"
VerticalOptions="Center"
Spacing="10"
IsVisible="{Binding ShowAdminButtons}">
<ImageButton
Source="delete.png"
WidthRequest="25"
HeightRequest="20"
Clicked="Delete_Clicked" />
<ImageButton
Source="write.png"
WidthRequest="25"
HeightRequest="20"
Clicked="EditButton_Clicked"/>
</HorizontalStackLayout>
</Grid>
<Border.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_event" CommandParameter="{Binding}"/>
</Border.GestureRecognizers>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ScrollView>
</RefreshView>
</Grid>
</ContentPage>
Xaml.cs часть:
using IbragimovLinux.DatabaseContext;
using IbragimovLinux.Entities;
using IbragimovLinux.ValidationPages;
namespace IbragimovLinux.Windows;
public partial class InstallationWindow : ContentPage
{
public InstallationWindow()
{
InitializeComponent();
}
protected override void OnAppearing()
{
RefreshCollectionView();
LoadData();
var roleId = ApplicationData.CurrentUser!.Id;
CheckRolePermissions();
}
private void CheckRolePermissions()
{
bool isAdmin = ApplicationData.CurrentUser?.RoleId == 1;
AddButton.IsVisible = isAdmin;
}
private void LoadData()
{
using (var db = new ApplicationDbContext())
{
var install = db.Installations.ToList();
if (ApplicationData.CurrentUser?.RoleId != 1)
{
foreach (var item in install)
{
item.ShowAdminButtons = false;
}
}
InstallationLV.ItemsSource = install;
}
}
private void AddButton_Clicked(object sender, EventArgs e)
{
AppShell.Current.GoToAsync(nameof(AddInfo), true);
}
private async void Delete_Clicked(object sender, EventArgs e)
{
if (ApplicationData.CurrentUser?.RoleId != 1)
{
await DisplayAlert("Ошибка", "Недостаточно прав для удаления", "OK");
return;
}
// Получаем статью для удаления
var button = (ImageButton)sender;
var article = (Installation)button.BindingContext;
// Запрашиваем подтверждение
bool confirm = await DisplayAlert(
"Удаление статьи",
$"Вы уверены, что хотите удалить статью \"{article.Title}\"?",
"Да", "Нет");
if (confirm)
{
try
{
// Удаляем из базы данных
using (var db = new ApplicationDbContext())
{
db.Installations.Remove(article);
await db.SaveChangesAsync();
LoadData();
}
await DisplayAlert("Успех", "Статья удалена", "OK");
}
catch (Exception ex)
{
await DisplayAlert("Ошибка", $"Не удалось удалить статью: {ex.Message}", "OK");
}
}
}
private void EditButton_Clicked(object sender, EventArgs e)
{
AppShell.Current.GoToAsync(nameof(EditPage), true);
}
private void RefreshData(object sender, EventArgs e)
{
RefreshCollectionView();
RefreshLV.IsRefreshing = false;
}
private void RefreshCollectionView()
{
ApplicationDbContext dbContext = new ApplicationDbContext();
InstallationLV.ItemsSource = dbContext.Installations.ToList();
}
private async void Tap_event(object sender, TappedEventArgs e)
{
if (sender is Border border && border.BindingContext is Installation installation)
{
DataTransfer.CurrentId = installation.Id;
DataTransfer.CurrentType = installation.TypeId;
await Navigation.PushAsync(new DetailPage());
}
}
}

