在我们使用MVVM开发项目时,免不了要用到绑定,但是数据通过绑定获取的时候,就不能再预览器里看到效果了,只能调试起来才能看到,这样就很麻烦。
我们可以通过 d.DataContext
来解决,这个属性仅在设计时应用 DataContext
。官网建议将此属性与 {x:Static}
指令结合使用,下面我们新建个MVVM模板的项目来看一下使用效果。
新建的项目视图上就有这个Design.DataContext
标签,默认值是写在ViewMode
里面,假如我们是个列表数据,就会显的 ViewModel
很臃肿了。所以我们使用官网建议的{x:Static}
来改一下。
首选改一下ViewModel
using System.Collections.ObjectModel;
namespace DesignDataDemo.ViewModels;
public class MainWindowViewModel : ViewModelBase
{
public string Greeting { get; set; }
public ObservableCollection<string> List { get; set; }
}
加一个静态的设计数据类
using System.Collections.ObjectModel;
using DesignDataDemo.ViewModels;
namespace DesignDataDemo;
public static class DesignData
{
public static readonly MainWindowViewModel DesignMainWindowViewModel = new()
{
Greeting = "Hello Avalonia",
List = new ObservableCollection<string>
{
"Hello",
"Avalonia",
"WPF"
}
};
}
View上指定DataContext
xmlns:dd="clr-namespace:DesignDataDemo"
d:DataContext="{x:Static dd:DesignData.DesignMainWindowViewModel}"
View完整代码
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:DesignDataDemo.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
xmlns:dd="clr-namespace:DesignDataDemo"
d:DataContext="{x:Static dd:DesignData.DesignMainWindowViewModel}"
x:Class="DesignDataDemo.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Icon="/Assets/avalonia-logo.ico"
Title="DesignDataDemo">
<StackPanel Spacing="20">
<TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center" />
<ItemsControl Items="{Binding List}" HorizontalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Foreground="Red"></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Window>
标签:DataContext,预览,namespace,public,using,DesignDataDemo,Avalonia
From: https://www.cnblogs.com/mchuang/p/17370757.html