[英]Binding a Command within a Datatemplate (XF/Prism)
對於Xamarin表單使用Prism,我有一個這樣的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中。
因此,綁定當然不會在這里起作用,因為綁定的上下文將是一個單獨的ConditionViewModel項。
我知道相對綁定在Xamarin中不可用,規定的解決方案似乎是直接應用{x:Reference SomeViewModel}。 但是使用Prism,View無法直接訪問其ViewModel,因此這是不可能的。
我還查看了此內容,以嘗試獲得RelativeContext標記擴展: https : //github.com/corradocavalli/Xamarin.Forms.Behaviors/blob/master/Xamarin.Behaviors/Extensions/RelativeContextExtension.cs但是,獲取RootObject為null的異常。
還有其他解決方案嗎?
如果我正確理解了您的問題,那么您想要的是這樣的:
視圖模型:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.