gpt4 book ai didi

c# - 在数据模板中绑定(bind)命令 (XF/Prism)

转载 作者:行者123 更新时间:2023-11-30 20:32:37 28 4
gpt4 key购买 nike

使用 Prism for Xamarin Forms,我有一个如下所示的 ListView:

<ListView ItemsSource="{Binding Conditions}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Margin="4" RowSpacing="0">
<Button Command="{Binding DoSomething}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

其中 Conditions 是 ConditionViewModel 的 ObservableCollection,DoSomething 命令位于页面的 ViewModel 中。

所以,当然,绑定(bind)在这里不起作用,因为它的绑定(bind)上下文将是一个单独的 ConditionViewModel 项。

我知道相对绑定(bind)在 Xamarin 中不可用,规定的解决方案似乎是直接应用 {x:Reference SomeViewModel}。但是使用 Prism,View 无法直接访问其 ViewModel,因此这是不可能的。

我也研究过这个,试图获得relativeContext标记扩展: https://github.com/corradocavalli/Xamarin.Forms.Behaviors/blob/master/Xamarin.Behaviors/Extensions/RelativeContextExtension.cs但是,出现 RootObject 为 null 的异常。

还有其他解决方案吗?

最佳答案

如果我正确理解你的问题,你想要的是这样的:

View 模型:

public class MyPageViewModel : BindableBase
{
public MyPageViewModel()
{
MyCommand = new DelegateCommand<MyModel>( ExecuteMyCommand );
}

public ObservableCollection<MyModel> Collection { get; set; }

public DelegateCommand<MyModel> MyCommand { get; }

private void ExecuteMyCommand( MyModel model )
{
// Do Foo
}
}

查看;

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyProject.Views.MyPage"
x:Name="page">
<ListView ItemsSource="{Binding Collection}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Command="{Binding BindingContext.MyCommand,Source={x:Reference page}}"
CommandParameter="{Binding .}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>

关于c# - 在数据模板中绑定(bind)命令 (XF/Prism),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41128701/

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