将命令/属性绑定到C#中的元素?

将命令/属性绑定到C#中的元素?,c#,xaml,mvvm,xamarin,C#,Xaml,Mvvm,Xamarin,我正在尝试在我的Xamarin表单应用程序中实现该功能。不幸的是,给定的示例使用XAML将视图与数据绑定,但我需要在代码隐藏中进行绑定 下面的代码用于选择图片并获取其源代码 public class CameraViewModel : XLabs.Forms.Mvvm.ViewModel { ... private ImageSource _imageSource; private Command _selectPictureCommand; public Im

我正在尝试在我的Xamarin表单应用程序中实现该功能。不幸的是,给定的示例使用XAML将视图与数据绑定,但我需要在代码隐藏中进行绑定

下面的代码用于选择图片并获取其源代码

public class CameraViewModel : XLabs.Forms.Mvvm.ViewModel
{
    ...
    private ImageSource _imageSource;
    private Command _selectPictureCommand;

    public ImageSource ImageSource
    {
        get { return _imageSource; }
        set { SetProperty(ref _imageSource, value); }
    }

    public Command SelectPictureCommand
    {
        get
        {
            return _selectPictureCommand ?? (_selectPictureCommand = new Command(
            async () => await SelectPicture(),() => true));
        }
    }
    ...
}
这些命令被绑定到XAML:

<Button Text="Select Image" Command="{Binding SelectPictureCommand}" />
<Image Source="{Binding ImageSource}" VerticalOptions="CenterAndExpand" />
我已通过执行以下操作成功绑定SelectPictureCommand:

Take_Button .Command = ViewModel.SelectPictureCommand;

但是,我怀疑它是否正确,同样的逻辑不能应用于ImageSource。

对于您拥有的按钮:

var Take_Button = new Button{ };
Take_Button.SetBinding(Button.CommandProperty, new Binding { Path = nameof(ViewModel.SelectPictureCommand), Mode = BindingMode.TwoWay, Source = ViewModel});
var Source_Image = new Image { };
Source_Image.SetBinding(Image.SourceProperty, new Binding { Path = nameof(ViewModel.ImageSource), Mode = BindingMode.TwoWay, Source = ViewModel });
对于您拥有的图像:

var Take_Button = new Button{ };
Take_Button.SetBinding(Button.CommandProperty, new Binding { Path = nameof(ViewModel.SelectPictureCommand), Mode = BindingMode.TwoWay, Source = ViewModel});
var Source_Image = new Image { };
Source_Image.SetBinding(Image.SourceProperty, new Binding { Path = nameof(ViewModel.ImageSource), Mode = BindingMode.TwoWay, Source = ViewModel });

我测试了这段代码,所以它应该可以工作。尝试调试当您按下按钮时是否调用SelectPictureCommand。只是想看看是否有命令分配给它。我把断点放在命令需要执行的地方(SelectPicture()),它不会被调用。Mode=BindingMode.TwoWay,Source=ViewModel-不知道如何或为什么,但将它添加到新绑定{}似乎可以解决所有问题。除非添加-Source=ViewModel-否则我的答案不会起作用。非常感谢你的帮助。