2017-11-24 10 views
2

은 내가 BindingContext를 같이 뷰 모델과 페이지가 : 나는 표시 할 수있는 유일한 역할 내 사용자 지정보기 구성 요소를 사용하여 내 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(); 
} 

뷰 모델은 명령이 있습니다 그리고 능력은 클릭해야합니다 :

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

을 내 CircleView.xaml.cs에서

내 CircleView.xaml에서 6,
... 
    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

이 시나리오는 귀하의 질문에 공식화 된 것과 약간 다릅니다. 귀하의 경우에는 사용자 정의 컨트롤에서 바인딩 가능한 속성을 만들고 싶습니다. – 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를 구현해야합니다 생각 :

도 참조하십시오.

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

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

당신은 다음 XAML에서 그 (X를주의를 바인딩 할 수 있습니다 :

1

당신은 CircleView에 바인딩 속성을 추가하여 CircleView에 뷰 모델에 대한 참조를 전달해야 이름이 일치해야합니다 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가 필요하지 않습니다.