corp-app/CORP-MAUI/ViewModels/PostViewModel.cs

118 lines
3.4 KiB
C#

using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using CORP_MAUI.Models;
namespace CORP_MAUI.ViewModels;
public class PostViewModel : INotifyPropertyChanged
{
public Post Post { get; }
public PostViewModel(Post post)
{
Post = post;
// Truncate content for preview
if (!string.IsNullOrEmpty(Post.Content) && Post.Content.Length > 0)
{
if (Post.Content.Length > 100)
{
_previewContent = Post.Content.Substring(0, 100) + "...";
}
else
{
_previewContent = Post.Content;
}
}
else
{
_previewContent = string.Empty;
}
}
private string? _localImagePath;
public string? LocalImagePath
{
get => _localImagePath;
set
{
_localImagePath = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsImageVisible));
OnPropertyChanged(nameof(DisplayImageSource));
}
}
private ImageSource? _imageSource;
public ImageSource? AuthorizedImageSource
{
get => _imageSource;
set
{
_imageSource = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsImageVisible));
OnPropertyChanged(nameof(DisplayImageSource));
}
}
public ImageSource? DisplayImageSource
{
get
{
if (_imageSource != null) return _imageSource;
if (!string.IsNullOrEmpty(_localImagePath) && File.Exists(_localImagePath))
{
// Basic check for empty files
try
{
if (new FileInfo(_localImagePath).Length == 0) return null;
}
catch { return null; }
// Используем FromStream для надежности, чтобы не блокировать файл
// и гарантировать чтение даже из системных папок
return ImageSource.FromStream(() =>
{
try
{
return new FileStream(_localImagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception ex)
{
Trace.WriteLine($"[PostViewModel] Error reading image {_localImagePath}: {ex.Message}");
return null;
}
});
}
return null;
}
}
public bool IsImageVisible => DisplayImageSource != null;
private string _previewContent;
public string PreviewContent
{
get => _previewContent;
set
{
_previewContent = value;
OnPropertyChanged();
}
}
// Proxy properties for cleaner XAML binding if needed, or bind to Post.Title directly
public int Id => Post.Id;
public string Title => Post.Title;
public string? AuthorizedImageUrl => Post.DisplayImageUrl;
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}