2016-01-13 63 views
1

我想在使用MVVM模式的UWP中创建一个应用程序。 有可能是用户控件是Listbox中的项目的DataTemplate将拥有自己的虚拟机。MVVM uwp UserControl与VM作为DataTemplate

这里是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); 
     } 
    } 

我想要的是例如如果我在我的UI中更改Id属性,则视图模型Id属性也将更改。

+0

您的ComponentUserControl需要一个(依赖性)属性,以便您可以执行'' –

+0

您可以更具体一些。我添加了这个道具,但我该如何使用它。我不知道它应该如何工作。 –

回答

3

克里斯说的是真的,你需要依赖属性来实现你想要的。

简而言之,您可以拥有两种类型的属性:您的ViewModel,Id和Name以及依赖项属性中的良好旧属性。 (当然也有附加属性,但概念上它们与依赖属性相同。)这两种属性之间的主要区别是,虽然两种类型都可以将数据绑定为,但只有依赖属性可以是来源的数据绑定。这正是你需要的。

因此,为了解决您的问题,我们需要一个依赖项属性,在您的控件的代码隐藏中定义。让我们把这种特性“组件”,像克里斯确实在他的回答是:

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); } 
} 

现在,如果你改变你的用户控件到这些你的绑定(注模式=单向,X:绑定默认情况下,一次性多!它here):

<TextBox Text="{x:Bind Component.Id, Mode=OneWay}" Grid.Row="0" /> 
<TextBox Text="{x:Bind Component.Name, Mode=OneWay}" Grid.Row="1" /> 

并更换的DataTemplate-S含量与一个克里斯提供:

<local:ComponentUserControl Component="{Binding}" /> 

魔术将发生,这一切都将正常工作! :) 如果您对此问题有任何疑问,请检查依赖项属性的this official overview

+0

我的项目源是类型组件不ComponentViewModel ...我的思想中也有一些逻辑错误,最后感谢您的答案我做到了。我还有一个问题,如果这个Component =“{Binding}”没有任何东西,在绑定datacontext后没有任何东西 –

+0

绑定需要DataContext作为开始点,如果你不告诉它明确地以另一种方式做它。因此,当您编写例如{Binding Id}时,它会绑定到控件的DataContext的Id属性。在这种情况下,ListView会根据您的DataTemplate设置它创建的每个项目的DataContext,因此在这种情况下,每个ComponentUserControl的DataContext都是一个Component(我的答案中为ComponentViewModel)。要将依赖项属性绑定到它,只需绑定到DataContext,就等于写入{Binding}。希望这可以帮助! –