【问题标题】:Binding a Command within a Datatemplate (XF/Prism)在数据模板中绑定命令 (XF/Prism)
【发布时间】:2017-04-28 23:06:23
【问题描述】:

将 Prism 用于 Xamarin 表单,我有一个这样的 ListView:

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

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

所以,当然,绑定在这里不起作用,因为它的 bindingcontext 将是一个单独的 ConditionViewModel 项。

我知道 Xamarin 中不提供相对绑定,并且规定的解决方案似乎是直接应用 {x:Reference SomeViewModel}。但是使用 Prism,View 不能直接访问它的 ViewModel,所以这是不可能的。

我也看过这个,试图获得一个 RelativeContext 标记扩展: https://github.com/corradocavalli/Xamarin.Forms.Behaviors/blob/master/Xamarin.Behaviors/Extensions/RelativeContextExtension.cs 但是,得到 RootObject 为空的异常。

还有其他解决方案吗?

【问题讨论】:

    标签: c# xamarin xamarin.forms prism


    【解决方案1】:

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

    视图模型:

    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>
    

    【讨论】:

    • 这正是我所需要的。谢谢谢谢!
    • 谢谢丹!!!!!!!!!!!!!!!!!!!!!你的救命稻草!!!!!!!!!!!!!!!!!!!!!!
    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 2010-12-28
    • 2015-05-08
    • 1970-01-01
    • 2012-10-31
    • 2011-03-12
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多