在C#中绑定命令/属性到元素?
问题描述:
我试图在我的Xamarin Forms App中实现XLabs CameraViewModel功能。不幸的是,给出的示例使用XAML将视图与数据绑定,但我需要在代码后面执行它。在C#中绑定命令/属性到元素?
以下代码用于选择图片并获取它的源代码。
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" />
如何申请相同的命令在代码隐藏创建的元素?
CameraViewModel ViewModel = new CameraViewModel();
var Take_Button = new Button{ };
Take_Button.SetBindings(Button.CommandProperty, //*???*//);
var Source_Image = new Image { };
Source_Image.SetBinding(Image.SourceProperty, //*???*//);
我已经成功地通过执行以下操作绑定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 });
我测试了这个代码,所以它应该工作。尝试调试,如果你按下SelectPictureCommand被调用的按钮。 – jzeferino
只是想看看是否有一个命令分配给它。我把断点放在命令需要执行的地方(SelectPicture()),它不会被调用。 – OverflowStack
模式= BindingMode.TwoWay,Source = ViewModel - 不知道如何或为什么,但将此添加到新的绑定{}似乎修复了一切。 – OverflowStack