CommandParameter
我在 .net maui 9 中有一个下面的小例子,其中我通过在视图中单击按钮时设置的值来设置视图模型中的属性。
然后将此属性用作视图的属性BindingContext
。因此,单击按钮时应显示的文本为。PlaceHolderText
Entry
Entry
Set PropertyOne
Text from Property
查看以下代码:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiBindingExample.MainPage"
xmlns:local="clr-namespace:MauiBindingExample.ViewModels">
<ScrollView>
<VerticalStackLayout
Padding="30,0"
Spacing="25">
<Image
Source="dotnet_bot.png"
HeightRequest="185"
Aspect="AspectFit"
SemanticProperties.Description="dot net bot in a hovercraft number nine" />
<Button
BindingContext="{local:ExampleViewModel}"
x:DataType="local:ExampleViewModel"
Text="Set PropertyOne"
Command="{Binding SetPropertyOneCommand}"
CommandParameter="Text from Property"/>
<Entry
BindingContext="{local:ExampleViewModel}"
x:DataType="local:ExampleViewModel"
PlaceholderColor="AliceBlue"
Placeholder="{Binding EntryPlaceholderText}"/>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
视图模型的代码如下:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace MauiBindingExample.ViewModels
{
public class ExampleViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string entryPlaceholderText;
public string EntryPlaceholderText
{
get => entryPlaceholderText;
set
{
entryPlaceholderText = value;
OnPropertyChanged();
}
}
public ICommand SetPropertyOneCommand { get; set; }
public ExampleViewModel()
{
SetPropertyOneCommand = new Command<string>(
(string arg) =>
{
EntryPlaceholderText = arg;
});
}
public void OnPropertyChanged([CallerMemberName] string propertyName="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
当我设置调试器时,我可以确认单击按钮时属性EntryPlaceholderText
设置正确Set PropertyOne
,但是在命令执行完成后,属性EntryPlaceholderText
被重置,因此没有Entry
显示占位符文本。
可能存在什么问题?
非常感谢您的帮助。