【问题标题】:Binding Command/Attribute To Element in C#?将命令/属性绑定到 C# 中的元素?
【发布时间】:2016-10-11 10:08:33
【问题描述】:

我正在尝试在我的 Xamarin Forms 应用程序中实现 XLabs CameraViewModel 功能。不幸的是,给定的示例使用 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" />

如何在代码隐藏中为创建的元素应用相同的命令?

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。

【问题讨论】:

    标签: c# xaml mvvm xamarin


    【解决方案1】:

    对于您拥有的按钮:

    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 - 不知道如何或为什么,但将其添加到 new Binding { } 似乎可以解决所有问题。
    • 除非添加 - Source = ViewModel - 否则我的答案将不起作用。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2013-09-03
    • 1970-01-01
    • 2017-02-26
    • 2011-02-23
    • 2018-07-13
    相关资源
    最近更新 更多