WPF在不使用任何框架去关联View和ViewModel的时候,最常用的2种写法是
this.DataContext=new MainViewModel();
或者
<Window.DataContext>
<viewModels:MainWindowViewModel/>
</Window.DataContext>
而之所以使用模板不起作用,是因为模板是针对UserControl的,例如
<DataTemplate DataType="{x:Type viewModels:HomeViewModel}">
<views:HomeView />
</DataTemplate>
要想使上面代码关联成功,那么HomeView必须是UserControl,
而唯一让我感觉吃惊的是AvaloniaUi组件库的使用,它源码使用了非常可观的方式去关联数据
这个和Prism异曲同工,都是配置大于约定,
prism配置方式如下
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="true"
AvaloniaUi
方式如下:
资源字典
<Application.DataTemplates>
<local:ViewLocator />
</Application.DataTemplates>
配置代码
public class ViewLocator
{
public static Control? Build(object? data)
{
if (data is null)
return null;
var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
var type = Type.GetType(name);
if (type != null)
{
var control = (Control)Activator.CreateInstance(type)!;
control.DataContext = data;
return control;
}
return new Control();
}
}
启动代码
public class Program
{
[STAThread]
public static void Main(string[] args)
{
Application app = new Application();
MainViewModel viewModel = new MainViewModel();
var main= ViewLocator.Build(viewModel) as Window;
app.Run(main);
}
}
标签:return,Mvvm,关联,var,new,WPF,data,public
From: https://www.cnblogs.com/guchen33/p/18147004