2014-10-27 112 views
0
<TextBlock x:Name="PageTitle" Text="{Binding tripTypeViewModel.test}"/> 

這是我對我的ViewModel測試中的一個屬性的XAML綁定。如何使綁定不指定ViewModel對象'tripTypeViewModel',因爲我將需要在運行時以編程方式更改數據上下文,所以它不會永遠是這樣嗎?如何正確設置xaml綁定

繼承人的全場景:

class CompositeViewModel 
{ 
    public static TripsResponseTypeViewModel tripsResponseTypeViewModel { get; set; } 
    public static TripTypeViewModel   tripTypeViewModel   { get; set; } 

    static CompositeViewModel() 
    { 
     tripsResponseTypeViewModel = new TripsResponseTypeViewModel(); 
     tripTypeViewModel   = new TripTypeViewModel(); 
    } 
} 

在我的Page.xaml我設置的數據上下文是這樣的:

public MyTripsPage() 
{ 
    this.InitializeComponent(); 

    this.DataContext = new CompositeViewModel(); 
} 

所以有的時候我想改變列表框的上tripTypeViewModel集合ItemsSource屬性或其他..這就是爲什麼我需要一個像CompositeViewModel的主類,但如何防止特定的XAML綁定?

+0

你不需要指定。如果'test'是你的viewModel屬性,被定義爲'PageTitle'的DataContext,那麼'{Binding test}'雖然如此,但是它不足以滿足 – 2014-10-27 15:24:38

+0

。它只在我指定VM對象時起作用。實際上,我的Page的DataContext被設置爲一個MasterClass,其中包含2個其他ViewModel對象,其中一個是tripTypeViewModel – 2014-10-27 15:26:54

+0

您確定'tripTypeViewModel'實際上是您的'DataContext',而不是您的DataContext上的屬性?發佈你設置'DataContext'的代碼... – 2014-10-27 15:28:45

回答

0

您可以爲所有可能的DataContext是一個通用的接口,並將其綁定到你的PageTitle

public class CompositeViewModel 
    { 
     public ITest SelectedViewModel { get; set; } 

     // Init the VM's and change them at run time ... 
    } 

    public class TripsResponseTypeViewModel : ITest 
    { 
     public string test { get; set; } 
    } 

    public class TripTypeViewModel : ITest 
    { 
     public string test { get; set; } 
    } 

    public interface ITest 
    { 
     string test { get; set; } 
    } 

在XAML

這樣,你要確保,無論什麼DataContextPageTitle使用它將始終有一個test屬性,您可以使用XAML綁定到