Xamarin Forms使用Prism在自定义控制器中绑定命令

时间:2018-05-02 10:39:31

标签: c# button xamarin.forms command

我遇到了一个问题,我无法弄明白。我有一个自定义控件,为了简化它,我想说我在一个框架内的框架内有一个按钮。我希望按钮的命令是可绑定的,按钮是私有的。所以,这是我的代码:

CustomControl.cs:

public System.Windows.Input.ICommand CommandInButton
{
    get { return ButtonInFrame.Command; }
    set { ButtonInFrame.Command = value; }
}

public static readonly BindableProperty CommandInButtonProperty = 
    BindableProperty.Create(
        propertyName:"CommandInButton",
        returnType: typeof(System.Windows.Input.ICommand),
        declaringType: typeof(CustomControl),
        defaultBindingMode: BindingMode.TwoWay);

private Button ButtonInFrame;

Myview.xaml:

<local:FrameButtonImage Grid.Column="0" Grid.Row="0"
                                ColorInButton="LightBlue"
                                SourceImageInButton="male.png"
                                IsSelected="{Binding IsMenSelected}"
                                CommandInButton="{Binding SelectMenCommand}"
                                />

MyViewModel.cs :(我使用Prism)

public DelegateCommand SelectMenCommand {get;私人集; }

public MainPageViewModel()
{
    SelectMenCommand = new DelegateCommand(SelectMen, CanSelectMen);
}
    private void SelectMen()
{
    System.Diagnostics.Debug.WriteLine("Hello men");
}

private bool CanSelectMen()
{
    return !IsMenSelected;
}

我的问题:它永远不会触发SelectMen()。

如果我在一个简单的按钮中绑定命令:

<Button Grid.Column="1" Grid.Row="0" Grid.RowSpan="3"
                Text=">"
                FontSize="Large"
                BackgroundColor="Transparent"
                HorizontalOptions="Center"
                VerticalOptions="Center"
                Command="{Binding SelectMenCommand}"/>

它的工作就像一个魅力!所以我认为我在CustomControl.cs中搞乱了......也许有人可以帮助我?谢谢 !

1 个答案:

答案 0 :(得分:1)

我找到了解决方法,但我确信它可以做得更好。我将我的命令设置为我的自定义控件的属性,并添加一个方法,将其设置为命令设置时按钮的命令。

CustomControl.cs:

public System.Windows.Input.ICommand CommandInButton
{
    get; set;
}

public static readonly BindableProperty CommandInButtonProperty =
    BindableProperty.Create(
        propertyName: "CommandInButton",
        returnType: typeof(System.Windows.Input.ICommand),
        declaringType: typeof(CustomControl),
        defaultValue: null,
        propertyChanged: CommandInButtonPropertyChanged);

private static void CommandInButtonPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var control = (CustomControl)bindable;
    control.ButtonInFrame.Command = (System.Windows.Input.ICommand)newValue;
}