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

标签 c# xamarin xamarin.forms prism

使用 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/

相关文章:

c# - 如何使键盘可滚动只读 WPF 文本框?

c# - TPL 和模拟

ios - 如何在 RowSelected 事件上导航到 Xamarin iOS 中的 ViewController

c# - Task.Run 然后使用 async await ContinueWith 在主线程替代上调用?

c# - TransactionScope 的层次结构

c# - 如何在 .Net Core 中使用客户端 SSL 证书

xamarin - 检测 Xamarin 表单中导航页面的后退箭头按下

ios - Xamarin iOS 找不到 sqlite 数据库的路径

c# - Xamarin 表单 ListView : Deselecting selected item by checking with OnTapped Event

c# - Xamarin - 将命令绑定(bind)到用户控件内对象的属性