[英]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.