2016-01-13 65 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}。希望這可以幫助! –