2015-04-15 83 views
7

我正在寫Xamarin應用程序,我發現WPF之間我不能跨越的區別。Xamarin表單綁定按鈕命令父BindingContext

我使用Xamarin Forms Labs來獲得Repeater控制。

我有一個轉發器,其中重複的DataTemplate:

<DataTemplate> 
    <Button Text="{Binding Text}" Command="{Binding CategorySelectedCommand}" /> 
</DataTemplate> 

但我想命令執行移動到我的用戶綁定上下文。

通常使用WPF它會是什麼樣子:

Command={Binding ElementName=myUserControl, Path=DataContext.CategorySelectedCommand} 

但它沒有ElementName屬性。

我發現,我可以這樣設置我的按鈕的BindingContext:

BindingContext="{x:Reference myUserControl}" 

但後來我Text屬性不能綁定到我的按鈕的文本。

我該怎麼做?

+0

代碼你找到一個解決的辦法?看起來'Source'不適用於DataTemplate。這也是一個真正的恥辱,使真正的MVVM難以實現。 – MrZander

+0

沒關係。我在更新後面。這似乎現在正在工作。 – MrZander

回答

11

您可以使用Source屬性來指定將使用的綁定的源代替當前的BindingContext。然後文本可以來自頁面的綁定上下文和來自其他地方的命令。

Command="{Binding CategorySelectedCommand, Source={x:Static me:SomeStaticClass.YourUserControl}}" 

Command="{Binding CategorySelectedCommand, Source={DynamicResource yourUserControlKey}}" 

Command="{Binding CategorySelectedCommand, Source={x:Reference myUserControl}}" 

這裏有一個完整的例子。一個常見的問題是不執行INotifyPropertyChanged並在之後設置屬性致電InitializeComponent()

XAML

<?xml version="1.0" encoding="UTF-8"?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="test.MyPage" x:Name="ThePage"> 
    <Label Text="{Binding TextProp, Source={x:Reference ThePage}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" /> 
</ContentPage> 

背後

public partial class MyPage : ContentPage 
{ 
    public MyPage() 
    { 
     this.TextProp = "Some Text"; 
     InitializeComponent(); 
    } 

    public string TextProp 
    { 
     get; 
     set; 
    } 
} 
+0

我有一個'ContentPage',它帶有x:Name'wireframe'。在這個頁面的ViewModel中,我有屬性'MainText'。 然後,在DataTemplate中我有標籤: '<標籤文本= 「{綁定源= {X:參考線框},路徑=的mainText}」>' 它不起作用。我也嘗試過'Path = BindingContext.MainText'。沒有成功 – Tomasz

+0

該屬性是否公開? – Krumelur

+1

當然是公開的 – Tomasz