При спробі використання .NET об’єктів у XMLSpy Script Editor можуть виникати складнощі, особливо коли мова йде про роботу з типами даних, такими як Guid. У цій статті ми розглянемо проблему, з якою зіштовхнувся один із…
У виниклій ситуації виявлено проблему з передачею константного цілого числа як параметра команди в .NET MAUI. Розглянемо цю проблему докладніше та запропонуємо можливі шляхи вирішення.
1 |
.NET MAUI Command won't fire when I pass constant integer as command parameter c# markup. I'm trying to pass an integer as a command parameter for a button command and the command isn't firing. I click and it does nothing. No exception. No compilation error. The breakpoint in my method doesn't get hit. I am using communitytoolkit.MAUI, communitytoolkit.MVVM, and communitytoolkit.Maui.Markup, although I'm not using it in my attempts below. I can successfully pass an entry text value. This works in my POC app. button.CommandParameter = new Binding(nameof(entry.Text), BindingMode.TwoWay, source: this); button.BindCommand(nameof(ClickCommand), source: this, nameof(EntryText), parameterSource: this); Most people use XAML, so I tried using interpreting the XAML into code: From: Using Command parameters <Button Text="5" Grid.Row="3" Grid.Column="1" Command="{Binding DigitCommand}" CommandParameter="5" /> So, I tried: getStartedButton.CommandParameter = 0; getStartedButton.BindCommand(nameof(GettingStartedButtonClickCommand), source: this); and const int Step = 0; getStartedButton.CommandParameter = new Binding(nameof(Step), BindingMode.TwoWay, source: this); getStartedButton.BindCommand(nameof(GettingStartedButtonClickCommand), source: this); and const int Step = 0; getStartedButton.CommandParameter = new Binding(nameof(Step), source: this); getStartedButton.BindCommand(nameof(GettingStartedButtonClickCommand), source: this); and const int Step = 0; getStartedButton.CommandParameter = new Binding(nameof(Step), source: this); getStartedButton.BindCommand(nameof(GettingStartedButtonClickCommand), source: this, nameof(Step), parameterSource: this); and several other variations. I hate asking for help, but I'm stumped and there's not a lot of examples using c# markup instead of XAML. I'm fairly new to .NET MAUI. This is my first time posting here, so I apologize if I am missing information or haven't formatted this properly. I expected the integer to be passed as a parameter to the method in the viewmodel. I've tested without a parameter and it works as expected. As I described, if I bind to an Entry text value, I can get the value. It's something with how I'm passing in the constant. I've read MSDN articles, I've read SO questions. Most examples are using XAML, so I've tried converting those. I've made several attempts using different variations to see if I could even just stumble on the answer. EDIT: I isolated the code and got it to work, kind of. I'll explain. In the viewmodel: public void OnButtonClickCommand(string arg) { Application.Current.MainPage.DisplayAlert("Button clicked", $"The button was clicked! Args:{arg}. EntryText property: {EntryText}", "Ok"); } In the mainpage. comboControl.ClickCommand = new Command<string>(viewModel.OnButtonClickCommand); In the buttoncontrol contentview. const int Step = 0; button.CommandParameter = 0; button.BindCommand(nameof(ClickCommand), source: this, nameof(Step), parameterSource: this); If I have the viewmodel method as an integer and the mainpage command as integer, as I'm expecting 0 to be, it doesn't work. If I change the viewmodel to string and the new command to string, it works. Is it because the command parameter breaks it down to an object and it assumes it's a string? Is there a way to pass it as an integer into the viewmodel method so that I don't have to convert it? |
Офіційна документація Microsoft чітко стверджує, що тип bool не є blittable. Документація також зазначає:
1 |
"Ви можете перевірити, чи є тип <em>blittable</em> або містить <em>blittable</em> вміст, спробувавши створити закріплену GCHandle. Якщо тип не є рядком або вважається не <em>blittable</em>, <code>GCHandle.Alloc</code> викине виняток <code>ArgumentException</code>." |
Тоді чому наступний код не викидає виняток для мене?
1 2 3 4 |
using System.Runtime.InteropServices; GCHandle.Alloc(new bool(), GCHandleType.Pinned).Free(); |
Причина цього поведінки полягає в оптимізації розміщення пам’яті, яку здійснює…
Під час розробки додатків у середовищі .NET MAUI Blazor Hybrid можуть виникати різноманітні труднощі, зокрема з розпізнаванням clr-namespace для компонентів. У цій статті ми розглянемо одну з таких проблем та запропонуємо рішення. Почнемо з виокремлення…
Minimal APIs стали популярним інструментом для швидкої розробки веб-додатків в середовищі .NET. Вони пропонують простий та ефективний спосіб створення API без зайвого навантаження. Однак, при використанні Minimal APIs разом з MediatR користувачі можуть стикнутися з…