gpt4 book ai didi

c# - 如何将 ListView 按钮的绑定(bind)上下文设置为 Xamarin Forms 中父级的绑定(bind)上下文

转载 作者:太空狗 更新时间:2023-10-29 22:05:05 25 4
gpt4 key购买 nike

基本上,我有一个带有 DataTemplate 选择器的 ListView,它使用基于 ListView 项目的特定 DataTemplate。

现在,在 DataTemplate 中 - 我有一个带有命令的按钮,它应该绑定(bind)到父级(或 ListView)本身的 ViewModel。

请注意,我只想绑定(bind)按钮的 Command 属性,因为 Text 和其他属性需要绑定(bind)到按钮的当前绑定(bind)上下文。

DataTemplate 的 BindingContext 是 ListView Item bindingContext(在本例中为消息模型),但我希望能够仅将数据模板中的特定按钮绑定(bind)到父 listView 的 View 模型。

我该怎么做?

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MobileMobile.Views.MobileMessageListView"
Title="Message List"
NavigationPage.BarBackgroundColor="#FF9100"
NavigationPage.BarTextColor="White"
xmlns:ViewSwitchers="clr-namespace:MobileMobile.ViewSwitchers;assembly=MobileMobile"
xmlns:ViewCells="clr-namespace:MobileMobile.ViewCells;assembly=MobileMobile"
xmlns:Extensions="clr-namespace:MobileMobile.Extensions;assembly=MobileMobile"
>

<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="botMessageDataTemplate">
<ViewCell>
<Button Text="Hello!" Command="{Binding TestCommand, Source=???}" CommandParameter="Hello"/>
</ViewCell>
</DataTemplate>

<ViewSwitchers:MobileMessageTemplateSwitcher x:Key="MobileMessageTemplateSwitcher" BotMessageDataTemplate="{StaticResource botMessageDataTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>

<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<StackLayout Grid.Row="0" Orientation="Vertical" x:Name="MainViewStack">
<ListView
CachingStrategy="RecycleElement"
BackgroundColor="Transparent"
ItemTemplate="{StaticResource MobileMessageTemplateSwitcher}"
IsPullToRefreshEnabled="true"
RefreshCommand="{Binding RefreshCommand}"
ItemsSource="{Binding Messages}"
HasUnevenRows="true"
IsRefreshing="{Binding IsLoading, Mode=OneWay}"
SeparatorVisibility="None">
<ListView.Footer/>
</ListView>
</StackLayout>
<StackLayout Grid.Row="1" Orientation="Horizontal" HeightRequest="50">
<Entry Text="{Binding CurrentMessageText}" Placeholder="{Binding MessageTextPlaceHolder}" HorizontalOptions="FillAndExpand"/>
<Button Text="SEND" Command="{Binding SendMessageCommand}"/>
</StackLayout>
</Grid>
</ContentPage.Content>
</ContentPage>

最佳答案

试试这个:

<Button
Text="Hello!"
Command="{Binding Path=BindingContext. TestCommand, Source={x:Reference Name=MessageListPage}}"
CommandParameter="Hello" />

您必须为页面提供一个值为 MessageListPagex:Name 属性,因此它会稍微扰乱您的纯 MVVM,但由于 Xamarin XAML 不会不支持相对绑定(bind)(据我所知..)这是要走的路。

关于c# - 如何将 ListView 按钮的绑定(bind)上下文设置为 Xamarin Forms 中父级的绑定(bind)上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com