подскажите, пожалуйста, почему ViewModel не работает?
Cтраница открывается, никаких ошибок (фатальных) не выдает
ViewModel:
public class PrivateChatsViewModel : BaseViewModel
{
private ObservableCollection<Models.Visual.MessageInPrivateChats> _chats = new();
private Task Init { get; set; }
public ObservableCollection<Models.Visual.MessageInPrivateChats> Chats
{
get => _chats;
set
{
if (_chats != value)
{
_chats = value;
OnPropertyChanged();
}
}
}
async Task init()
{
while (true)
{
await Task.Run(() =>
{
});
await Task.Delay(2000);
}
}
public PrivateChatsViewModel()
{
IsLoading = true;
if (!server.IsHasConnection())
{
IsLoading = false;
IsHasNotConnection = true;
}
else
{
IsHasNotConnection = false;
if (!server.IsHasMessages())
{
IsHasNotData = true;
IsLoading = false;
}
else
{
IsHasNotData = false;
List<Models.Message> list = server.GetChats();
Console.WriteLine($"List length: {list.Count}"); //строки нет в Debug'e
foreach (var item in list)
{
Models.Visual.MessageInPrivateChats message = new()
{
DialogID = item.dialogId,
MessageID = item.messageId,
LastMessageText = item.message,
notReadedCount = item.notReadedCount,
isHasNotReaded = item.notReadedCount > 0,
ImageStatusResource = getStatusImageResourceByMessageStatus(item.status),
TimeBeforeLastMessage = getTimeBefore(item.sendedAt),
UserNameSurname = item.userName,
UserImageResource = item.imageResource
};
_chats.Add(message);
}
Chats = _chats;
Console.WriteLine($"Chats length: {Chats.Count}"); //строки нет в Debug'e
}
}
}
...
}
BaseViewModel:
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
Services.Server ser;
protected Services.ServerGets server;
public BaseViewModel()
{
ser = new();
server = new(ser);
}
private bool _isHasNotData;
private bool _isHasNotConnection;
private bool _isLoading;
public Command Reload { get; set; }
public bool IsLoading
{
get => _isLoading;
set
{
_isLoading = value;
OnPropertyChanged();
}
}
public bool IsHasNotData
{
get => _isHasNotData;
set
{
_isHasNotData = value;
OnPropertyChanged();
}
}
public bool IsHasNotConnection
{
get => _isHasNotConnection;
set
{
Shell.Current.DisplayAlert("Ошибка", "Отсутствует соединение, попробуйте, пожалуйста, позже", "OK");
_isHasNotConnection = value;
OnPropertyChanged();
}
}
public bool NotIsLoading
{
get => !_isLoading;
}
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
View:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ProDom.MobileClient.Chats.ChatsPrivatePage"
Shell.TabBarBackgroundColor="#ac88ec"
xmlns:viewmodels="clr-namespace:ProDom.MobileClient.ViewModels"
xmlns:models="clr-namespace:ProDom.MobileClient.Models.Visual"
x:DataType="viewmodels:PrivateChatsViewModel">
<Shell.TitleView>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="1"/>
</Grid.ColumnDefinitions>
<HorizontalStackLayout
Grid.Column="0"
IsVisible="{Binding IsLoading}"> // наслаиваются друг на друга
<Label
Text="Обновление"
TextColor="White"
FontSize="18"
FontAttributes="Bold"
VerticalOptions="Center"
Margin="15,0,0,0"/>
<Image
Source="loading.gif"
IsAnimationPlaying="True"
WidthRequest="50"
HeightRequest="50"
Aspect="AspectFill"
Margin="10,0,0,0"/>
</HorizontalStackLayout>
<Label
IsVisible="{Binding NotIsLoading}" // наслаиваются друг на друга
Grid.Column="0"
Text="Чаты"
TextColor="White"
FontSize="18"
FontAttributes="Bold"
VerticalOptions="Center"
Margin="15,0,0,0"
/>
</Grid>
</Shell.TitleView>
Извините, что так много кода, не знаю, что конкретно не работает... Спасибо!
DataContext, это единственное что я вижу. – EvgeniyZ Nov 18 '22 at 18:59ViewModelне привязывается коView, ожидаю, что данные изViewModelбудут поступать вContentPage. НасчетDataContext, по-моему, в MAUI аналог этомуx:DataType, который задан (проDataContextв доках MAUI информации не нашел) – StudyAndroid Nov 18 '22 at 19:14DataContext(зову по привычке из WPF) являетсяBindingContext, в документации прям есть целый раздел про привязки. Вы наверно захотите задать его в XAML, я вам на этот случай дам этот ответ. – EvgeniyZ Nov 18 '22 at 19:27