我正在尝试使用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
现在它是我的UserControl
<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);
}
}
我想要的是,例如,如果我在UI中更改Id
属性,则视图模型Id
属性也将更改。
Kris说的是真的,你需要依赖属性来实现你想要的。
简而言之,您可以有两种类型的属性:像ViewModel中的Id和Name这样的好的旧属性,以及依赖属性。(当然,也有附加属性,但从概念上讲,它们与依赖属性相同。)这两种类型的属性之间的主要区别在于,虽然这两种属性都可以是数据绑定的目标,但只有依赖属性可以是数据结束的源。这正是你所需要的。
因此,为了解决您的问题,我们需要一个依赖属性,该属性在控件的代码中定义。让我们把这个属性称为"组件",就像Kris在他的回答中所做的那样:
public static readonly DependencyProperty ComponentProperty = DependencyProperty.Register(
"Component",
typeof(ComponentUserControlViewModel),
typeof(ComponentUserControl),
new PropertyMetadata(null));
public ComponentUserControlViewModel Component
{
get { return (ComponentUserControlViewModel) GetValue(ComponentProperty); }
set { SetValue(ComponentProperty, value); }
}
现在,如果您将UserControl上的绑定更改为这些(注意模式=单向,x:Bind默认为OneTime!更多信息请点击此处。):
<TextBox Text="{x:Bind Component.Id, Mode=OneWay}" Grid.Row="0" />
<TextBox Text="{x:Bind Component.Name, Mode=OneWay}" Grid.Row="1" />
并将您的DataTemplate-s内容替换为Kris提供的内容:
<local:ComponentUserControl Component="{Binding}" />
魔法会发生,所有这些都会奏效!:)如果您对此还有任何疑问,请查看此依赖属性的官方概述。