XAML 在MAUI中将父函数传递给函数,绑定问题

5anewei6  于 2023-03-06  发布在  其他
关注(0)|答案(2)|浏览(143)

我正在尝试解决. NET MAUI中的绑定问题。
如屏幕截图1所示,我有学生卡信息。第一个字段是标签,然后它们转到三个条目。我们的想法是,当用户单击按钮时,这三个条目应该是可读的,编辑按钮应该替换为提交按钮。
Screenshot 1 - Student Card Information
在本例中,我需要向EditButton事件函数传递一个父函数(stacklayout)。
XAML页的切片如下所示:

<Grid  ColumnDefinitions="3*,1*" BackgroundColor="{StaticResource cardbg}" RowSpacing="3">
       <StackLayout Grid.Row="0" Grid.Column="0" x:Name="StudentStack" 
                                                 Margin="20">                                                                                          
         
        <Label x:Name ="idlab" Text="{Binding StudentId, StringFormat='Id={0:D0}'}" TextColor="   {StaticResource cardtextbg}"/>
        <Entry Text="{Binding StudentName}" TextColor="{StaticResource cardtextbg}" IsReadOnly="True"/>
         <Entry Text="{Binding StudentSurname}" TextColor="{StaticResource cardtextbg}" IsReadOnly="True"/>
         <Entry Text="{Binding StudentGPA}" TextColor="{StaticResource cardtextbg}"
                                               IsReadOnly="True"
                                               Margin="10"/>
         </StackLayout>

         
         <ImageButton x:Name="edit"   Grid.Row="0" Grid.Column="1"                                                
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:StudentsViewModel}}, Path=EditStudents}"
CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type models:Student}}}"                                                 
HeightRequest="{Binding Height, Source={x:Reference idlab}}"                                               
Source="edit.svg"  
BackgroundColor="CornflowerBlue">                                                                                            
         </ImageButton>
</Grid>

因此,卡是一个2列1行的网格,其中有一个堆栈布局,图像按钮在卡的右侧。
我尝试了以下代码来绑定我的ImageView以传递父对象。
XAML:

Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:StudentsViewModel}}, Path=EditStudents}"
CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type models:Student}}}"

学生视图模型:

public ICommand EditStudents { get; set; }

 public StudentsViewModel()
 {
   EditStudents = new Command(onEditStudents);
 }
private void onEditStudents(object obj)
{
   var b = 3 + 4;
}

该对象表示Student模型,但它不是StackLayout的对象,因此我无法在单击EditButton时打开/关闭特定卡片的条目。
那是我的问题。
同样,由于打开/关闭3个条目的可读属性,我如何将XAML页面绑定到ViewModel,并传递StackLayout(特定卡片的父级)?
功能要怎么样?

j1dl9f46

j1dl9f461#

喜欢下面的评论你的问题已经提到。
将您的CommandParameter绑定到实际的StudentModel,然后更改会影响视觉行为的属性

i1icjdpr

i1icjdpr2#

我建议你阅读一读:
https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/relative-bindings?view=net-maui-7.0
最重要的是,关注这一部分:https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/relative-bindings?view=net-maui-7.0#bind-to-an-ancestor
我看到你有:

{Binding StudentName}

它正在起作用...
绑定学生的方式应该是:

{Binding .}

相关问题