C# 如何正确设置xaml绑定

C# 如何正确设置xaml绑定,c#,xaml,mvvm,binding,windows-phone,C#,Xaml,Mvvm,Binding,Windows Phone,在my Page.xaml中,我将数据上下文设置为: class CompositeViewModel { public static TripsResponseTypeViewModel tripsResponseTypeViewModel { get; set; } public static TripTypeViewModel tripTypeViewModel { get; set; } static CompositeVie

在my Page.xaml中,我将数据上下文设置为:

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

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

因此,有时我想更改tripTypeViewModel集合或其他集合上ListBox的ItemsSource属性。。这就是为什么我需要像CompositeViewModel这样的主类,但是如何防止XAML特定的绑定呢?

您可以为所有可能的
DataContext
创建一个公共接口,并将其绑定到您的
PageTitle

public MyTripsPage()
{
    this.InitializeComponent();

    this.DataContext = new CompositeViewModel();
}
在xaml中


通过这种方式,您可以确保无论
DataContext
PageTitle
使用什么,它始终具有一个
test
属性,您可以使用XAML绑定该属性,而无需指定该属性。如果
test
是viewModel上定义为
PageTitle
的DataContext的属性,那么
{Binding test}
就足够了,尽管如此,但它并不足够。仅当我指定VM对象时,它才起作用。。实际上,我的页面的DataContext设置为一个MasterClass,其中包含两个其他ViewModel对象,其中一个是tripTypeViewModel。您确定
tripTypeViewModel
实际上是您的
DataContext
而不是DataContext上的属性吗?在设置
DataContext
的位置张贴代码,这就是情况。如何修复它,因为我需要将页面中某些元素的ItemsSource动态更改为ViewModel主类中的属性。
public MyTripsPage()
{
    this.InitializeComponent();

    this.DataContext = new CompositeViewModel();
}
    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; } 
    }