【发布时间】:2020-07-10 15:11:41
【问题描述】:
我正在使用媒体插件并且一切正常,直到我决定将我的逻辑移至 ViewModel。
这是我的 Xaml
<Frame BackgroundColor="LightGray" HasShadow="True">
<Image
x:Name="Photo"
Grid.Row="2"
HeightRequest="100"
Source="{Binding postViewModel.SelectedPhoto}"
VerticalOptions="Start"/>
</Frame>
我与 MasterViewModel 的绑定
MasterPostsViewModel ViewModel;
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = ViewModel = new MasterPostsViewModel(Navigation);
}
我的主人
class MasterPostsViewModel : BaseViewModel
{
public PostViewModel postViewModel { get; set; }
public CategoriesViewModel categoriesViewModel { get; set; }
public MasterPostsViewModel(INavigation navigation)
{
postViewModel = new PostViewModel();
categoriesViewModel = new CategoriesViewModel();
postViewModel = new PostViewModel(navigation);
}
}
在视图模型中拍照
private MediaFile _selectedPhoto;
public MediaFile SelectedPhoto { get => _selectedPhoto; set => SetValue(ref
_selectedPhoto, value); }
private async Task TakePicture()
{
await Permission();
var imageSource = await DependencyService.Get<IMessage>().ShowActionSheet(AppResources.AlertPhoto, AppResources.AlertNewPhoto, AppResources.AlertGallery);
if (imageSource == AppResources.AlertNewPhoto)
{
var imageFileName = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions()
{
Name = $"{DateTime.UtcNow}.jpg",
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear,
PhotoSize = PhotoSize.Medium,
SaveToAlbum = true
});
if (imageFileName == null) return;
else
{
SelectedPhoto = imageFileName;
}
}
}
我可以看到图片的地址,但是图片没有显示在我的 xaml 中。我试图遵循这个 Bind Plugin.Media fromViewModel
但是还是不行。请对我做错了什么提出一些建议
【问题讨论】:
-
看起来你在每次显示页面时都在创建一个新的视图模型,所以引用总是不同的,你永远不会看到图像,因为你正在查看一个新的实例视图模型。确保您只设置一次视图模型并为您的图像属性设置
INotifyPropertyChanged -
你好,我不应该使用这个吗? BindingContext = ViewModel = new MasterPostsViewModel(Navigation);
-
没错。只需创建一次
MasterPostsViewModel,将其分配给BindingContext,它应该可以工作 -
很抱歉,没有变化
-
你在哪里打电话给 TakePicture?你在使用绑定命令吗?
标签: xamarin.forms