2013-12-10 21 views
1

我有一點連接兩種組分的麻煩:如何綁定用戶控件到視圖模型

查看:

<UserControl x:Class="CoolPlaces.Views.ListItem" 
    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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    d:DesignHeight="480" d:DesignWidth="480"> 

    <ListBox ItemsSource="{Binding ListViewModel}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel> 
        <TextBlock Text="{Binding Path=Name, Mode=OneWay}" /> 
        <TextBox Text="{Binding Path=Description, Mode=OneWay}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</UserControl> 

的部分主頁查看:在我上面包括用戶控制:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
    <views:ListItem Height="300" /> 
</Grid> 

視圖模型:

namespace CoolPlaces.ViewModels 
{ 
    public class ListViewModel : INotifyPropertyChanged 
    { 
     private ObservableCollection<BasicModel> _places; 

     public ObservableCollection<BasicModel> Places { 
      get { 
       return _places; 
      } 
      set { 
       _places = value; 
       RaisePropertyChanged("Places"); 
      } 
     } 

     public ListViewModel() { 
      Places = new ObservableCollection<BasicModel>(_loadPlaces()); 
     } 

     private IEnumerable<BasicModel> _loadPlaces() { 
      return //some hard coded objects 
     } 
    } 
} 

的MainPage

namespace CoolPlaces 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
     private ListViewModel vm; 

     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 
      vm = new ListViewModel(); 
     } 
    } 
} 

回答

2

你靠近。您需要將DataContext設置爲等於您的ViewModel。

public partial class MainPage : PhoneApplicationPage 
{ 
    private ListViewModel vm; 

    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
     DataContext = vm = new ListViewModel(); 
    } 
} 

然後你的ListBox不需要綁定它。相反,將其綁定到您的ViewModel上的Places屬性:

<ListBox ItemsSource="{Binding Places}"> 
+0

我照你的建議做了,但它仍然不起作用。順便說一句。我的ListItem視圖如何知道我綁定到ListViewModel上的位置屬性? –

+0

@MarekMałek我編輯了我的答案。現在就試試。 – gleng

+1

太簡單了......謝謝! –

相關問題