我将尝试使用MVVM模式在UWP中创建一个应用程序。
Listbox的每个项目都有一个DataTemplate,此处可能有一个用户控件(usercontrol),它拥有自己的VM。
下面是MainPage.xaml的一部分:
<ListBox Name="ListBox1" ItemsSource="{Binding Components}">
<ListBox.ItemTemplate >
<DataTemplate x:DataType="vm:ComponentUserControlViewModel" >
<local:ComponentUserControl />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MainPageVM包含以下内容:
public ObservableCollection<Component> Components
现在这是我的用户控件
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox Text="{Binding Id}" Grid.Row="0"></TextBox>
<TextBox Text="{Binding Name}" Grid.Row="1"></TextBox>
</Grid>
VM:
public class ComponentUserControlViewModel : ViewModelBase
{
private string _componentId;
private string _componentName;
public ComponentUserControlViewModel()
{
}
public string Id
{
get { return _componentId; }
set
{
SetProperty(ref _componentId, value);
}
}
public string Name
{
get { return _componentName; }
set
{
SetProperty(ref _componentName, value);
}
}
我希望的是,例如,如果我在我的用户界面中更改
Id
属性,那么视图模型Id
属性也会随之更改。
<local:ComponentUserControl Component="{Binding}" />
。 - Kris Vandermotten