Issue
As a complete beginner to XAML/MVVM I would like to request some help with implementing a 24x14 letter screen.
The XAML implementation is quite easy I think with something like
<Grid x:Name="ScreenGrid"
RowDefinitions="*, *, *, *, *, *, *, *, *, *, *, *, *, *"
ColumnDefinitions="*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*"/>
However what I am struggling with is the Data Binding.
I would like to write something like an "UpdateScreen()" Method, that populates that grid with data where
- Every Grid-Cell has 1 Letter
- Every letter has a color (red, green, ...)
- Every letter is either big or small
My current ViewModel looks like this (with the help of Microsoft.Toolkit.Mvvm):
public partial class ScreenViewModel : ObservableObject
{
[ObservableProperty]
private ScreenText[] _screen;
//ScreenText consists of char value, Color color, bool isBig
[ICommand]
private void ButtonPressed(AppButton button)
{
System.Diagnostics.Debug.WriteLine($"Button {button} was pressed");
}
private void UpdateScreen()
{
[.?.]
}
}
Which is supposed to communicate with the actual logic of the app, which generates a ScreenText[], that is passed back to the ViewModel.
How do I wire this up to the ScreenGrid?
Thanks for your help.
Solution
The solution for me (minimal example) looks like this:
In the XAML the grid gets defined like this
<Grid x:Name="ScreenGrid"
RowDefinitions="*, *, *, *, *, *, *, *, *, *, *, *, *, *"
ColumnDefinitions="*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*"/>
The ViewModel looks like this (with the help of Toolkit.Mvvm):
public partial class ScreenViewModel : ObservableObject
{
const int LINES = 14;
public ObservableCollection<ScreenText> Screen { get; } = new ObservableCollection<ScreenText>();
public ScreenViewModel()
{
for (int i = 0; i < LINES; i++)
{
Screen.Add(new ScreenText());
}
}
[ICommand]
private void ButtonPressed(AppButton button)
{
System.Diagnostics.Debug.WriteLine($"Button {button} was pressed");
//Do some business logic and manipulate the screen
OnPropertyChanged(nameof(Screen));
}
}
And finally the MainPage.Xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
//Setup Screen
AddScreenCells();
}
private void AddScreenCells()
{
for (int row = 0; row < ScreenGrid.RowDefinitions.Count; row++)
{
for (int col = 0; col < ScreenGrid.ColumnDefinitions.Count; col++)
{
Label label = new Label();
label.SetBinding(Label.TextProperty, $"{nameof(ScreenViewModel.Screen)}[{row}].{nameof(ScreenText.Letters)}[{col}]");
ScreenGrid.Add(label, col, row);
}
}
}
}
Answered By - Dokug
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.