簡體   English   中英

Xamarin Forms使用Prism在自定義控件中綁定命令

[英]Xamarin Forms bind a command in a custom controler with Prism

我遇到了一個問題,無法解決。 我有一個自定義控件,為簡化起見,假設我在框架內部有一個按鈕。 我希望按鈕的命令是可綁定的,並且按鈕是私有的。 所以,這是我的代碼:

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 :(我正在使用棱鏡)

公共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中搞砸了……也許有人可以幫助我? 謝謝 !

我找到了解決方法,但我敢肯定有可能做得更好。 我將命令設置為自定義控件的屬性,並在設置命令時添加一種方法以將其設置為按鈕的命令。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM