如何正确设置 xaml 绑定
本文关键字:绑定 xaml 设置 何正确 | 更新日期: 2023-09-27 18:27:56
<TextBlock x:Name="PageTitle" Text="{Binding tripTypeViewModel.test}"/>
这是我与视图模型测试中的属性的 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集合或其他集合上更改ListBox的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
使用什么,它始终具有可以使用 XAML 绑定到的 test
属性