我在WPF应用程序中使用MVVM模式以允许全面的单元测试.MVVM模式本身是伟大的工作,但我挣扎中,这意味着我可以使用设计时数据支持WPF的方式相适应的模式.
当我使用Prism时,ViewModel实例通常被注入到视图的构造函数中,就像这样
public MyView(MyViewModel viewModel)
{
DataContext = viewModel;
}
Run Code Online (Sandbox Code Playgroud)
然后将ViewModel的依赖项注入构造函数中,就像这样
public class MyViewModel
{
public MyViewModel(IFoo foo, IBar bar)
{
// ...
}
// Gets and sets the model represented in the view
public MyModel { get; set; }
// Read-only properties that the view data binds to
public ICollectionView Rows { get; }
public string Title { get; }
// Read-write properties are databound to the UI and are used to control logic
public string Filter { get; …Run Code Online (Sandbox Code Playgroud) 我有一个包含ListBox的WPF窗口.ItemsSource绑定到视图模型的属性.
<Window x:Class="SimpleWpfApp.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding MainWindowViewModel, Source={StaticResource Locator}}">
<DockPanel>
<ListBox ItemsSource="{Binding SomeThings}" />
</DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
视图模型的属性是自定义接口的可观察集合; ISomeInterface.界面非常简单,由SomeClass实现,它还会覆盖ToString.
public class MainWindowViewModel
{
public ObservableCollection<ISomeInterface> SomeThings
{
get
{
var list = new List<ISomeInterface>
{
new SomeClass {Value = "initialised"},
new SomeClass {Value = "in"},
new SomeClass {Value = "code"}
};
return new ObservableCollection<ISomeInterface>(list);
}
}
}
public interface ISomeInterface
{
string Value { get; }
}
public class SomeClass : ISomeInterface
{
public string …Run Code Online (Sandbox Code Playgroud)