在MvvmLight中View和ViewModel的绑定
View Model
public class Test1ViewModel : ViewModelBase {
public List<string> Name = new List<string> (){"amos","kai","name"};
...
}
public class Test2ViewModel : ViewModelBase {
public List<string> Name1 = new List<string> (){"amos1","kai1","name1"};
...
}
public class Test3ViewModel : ViewModelBase {
public List<string> Name2 = new List<string> (){"amos2","kai2","name2"};
...
}
app.xml中
<Application.Resources>
<ResourceDictionary>
<vms:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>
</Application.Resources>
在ViewModelLocator
中配置ViewModel
。
public class ViewModelLocator{
public ViewModelLocator(){
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<Test1ViewModel>();
SimpleIoc.Default.Register<Test2ViewModel>();
SimpleIoc.Default.Register<Test3ViewModel>();
}
public Test1ViewModel Test1 {
get{
return ServiceLocator.Current.GetInstance<Test1ViewModel>();
}
}
public Test2ViewModel Test2 {
get{
return ServiceLocator.Current.GetInstance<Test2ViewModel>();
}
}
public Test3ViewModel Test3 {
get{
return ServiceLocator.Current.GetInstance<Test3ViewModel>();
}
}
}
<Window
x:Class="Wisdy.DSP.Client.FormulaContentEdit"
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:local="clr-namespace:Wisdy.DSP.Client"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding Source={StaticResource Locator}, Path=OffLine}"
mc:Ignorable="d">
1.一个ViewModel对应一个View
DataContext="{Binding Source={StaticResource Locator}, Path=Test1}"
当配置一个viewmodel
的时候,直接配置Path=Test1
,就可以在xaml
中绑定viewmodel
中的数据了。
如:
<ListBox ItemsSource="{Binding Name}"/>
1.多个ViewModel对应一个View
DataContext="{Binding Source={StaticResource Locator}}"
当配置多个viewmodel
的时候,就不配置Path
,但是在xaml
中绑定viewmodel
中的数据需要调用。
如:
<ListBox ItemsSource="{Binding Test1.Name}"/>
<ListBox ItemsSource="{Binding Test2.Name}"/>
<ListBox ItemsSource="{Binding Test3.Name}"/>