繁体   English   中英

如何正确设置XAML绑定

[英]How to set xaml binding properly

<TextBlock x:Name="PageTitle" Text="{Binding tripTypeViewModel.test}"/>

这是我对ViewModel测试中的属性的XAML绑定。 如何使绑定不指定ViewModel对象“ tripTypeViewModel”,因为我将需要在运行时以编程方式更改数据上下文,所以不会总是这样吗?

这是完整的场景:

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集合或其他类型上ListBoxes的ItemsSource属性。这就是为什么我需要像CompositeViewModel这样的主类,但是如何防止XAML特定的绑定呢?

您可以为所有可能的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中

这样,您可以确保无论使用哪种DataContext PageTitle它都将始终具有一个test属性,您可以使用XAML将该属性绑定到该属性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM