2013-12-10 5 views
1

Я имею немного неприятности, соединяющей оба компонента:Как связать UserControl с ViewModel

Вид:

<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> 

ViewModel:

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 не нужно быть связанным с ним. Вместо этого, привязать его к Places собственности на вашем ViewModel:

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

Я сделал, как вы предложили, но он все равно не будет работать. Btw. как мое представление ListItem знает, что я привязываюсь к свойствам мест в ListViewModel? –

+0

@ MarekMałek Я отредактировал свой ответ. Попробуй это сейчас. – gleng

+1

Так просто ... Спасибо! –

Смежные вопросы