2017-11-24 1 views
2

は私がBindingContextをとのViewModelとページを持っている:私は表示させるだけで機能します私のカスタムビューコンポーネントを使用して、私のPage.xamlをでXAMLでコマンドを渡すには?

public class ViewModel : INotifyPropertyChanged 
{ 
    ... 
    public ICommand SomeCommand { get; set; } 

    public ViewModel() 
    { 
     SomeCommand = new Command((object data) => {}); 
    } 
    ... 
} 

public Page() 
{ 
    InitializeComponent(); 

    this.BindingContext = new ViewModel(); 
} 

ViewModelには、コマンドを持っていますそして、クリックする能力があります:私のCircleView.xaml.cs

<local:CircleView 
    Radius="20" 
    InnerText="Click me" 
    InnerTextSize="15" 
    TapCommand="{Binding SomeCommand}" 
/> 

を私CircleView.xamlで

... 
    public ICommand TapCommand { get; set; } 
... 

:私はプログラムを実行すると

... 
<TapGestureRecognizer 
    Command="{Binding Path=TapCommand, Source={x:Reference Name=CircleView}}" 
    CommandParameter="{Binding Path=InnerText, Source={x:Reference Name=CircleView}}" 
/> 
... 

私は「... TapCommandが見つかりませんプロパティ、バインド可能なプロパティ、またはイベント、または不一致」エラーが発生します。 XAMLでコマンドを渡すにはどうすればよいですか?

+1

このシナリオは、あなたの質問でどのように策定されているかとは少し異なります。あなたの場合は、あなたのusercontrolでバインド可能なプロパティを作成する。 – Stefan

答えて

2

依存関係プロパティとしてTapCommandをユーザーコントロールに追加する必要があります。これをCircleView.xaml.csに追加し、以前に定義したTapCommandを削除してください。

参照:dependency-properties-overview

//making is a bindab 
public static readonly DependencyProperty TapCommandProperty = 
    DependencyProperty.Register("TapCommand", typeof(ICommand), typeof(CircleView) 
      /* possible more options here, see metadata overrides in msdn article*/); 

public ICommand TapCommand 
{ 
    get { return (ICommand)GetValue(TapCommandProperty); } 
    set { SetValue(TapCommandProperty, value); } 
} 

その後、私はわからないが、あなたはあなたのTapGestureRecognizerTapCommandを使用しているので、私はあなたが同様にあなたのCircleViewにINotificationChangedを実装する必要がありますだと思います。

1

あなたはCircleViewにバインド可能プロパティを追加することによって、CircleViewへのViewModelへの参照を渡す必要があります:

public static BindableProperty ParentBindingContextProperty = 
    BindableProperty.Create(nameof(ParentBindingContext), typeof(object), 
    typeof(CircleView), null); 

public object ParentBindingContext 
{ 
    get { return GetValue(ParentBindingContextProperty); } 
    set { SetValue(ParentBindingContextProperty, value); } 
} 

あなたはその後、Xの点に注意してください(あなたのXAMLでそれをバインドすることができます。名前は、xと一致する必要があります:参考):

<ContentView ... x:Name="Home" ... > 
    ... 
    <local:CircleView ParentBindingContext="{Binding Source={x:Reference Home}, Path=BindingContext}"/> 

そして最後に、あなたのCircleViewであなたのXAMLであなたの「親」ビューモデルにコマンドにあなたのタップジェスチャーをバインド:

<TapGestureRecognizer BindingContext="{Binding Source={x:Reference CircleView}, Path=ParentBindingContext}" Command="{Binding Path=TapCommand}" CommandParameter="{Binding Path=InnerText, Source={x:Reference Name=CircleView}}" /> 

CircleViewにTapCommandは必要ありません。

関連する問題