2014-10-13 3 views
0

Я пытаюсь привязать данные к форме WPF с помощью паттерна MVVM. Но я пробовал разные способы, и я не могу заставить кого-нибудь работать правильно. Так может ли кто-нибудь дать мне решение за то, что мне не хватает?Связывание данных с формой WPF, MVVM

MainWindow.xaml

<Window x:Class="MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:vm="clr-namespace:MoneyManager.WPF.ViewModels" 
WindowStartupLocation="CenterScreen" 
Title="MainWindow" Height="500" Width="300"> 
<Window.Resources> 
    <DataTemplate x:Key="CategoryModelTemplate"> 
     <StackPanel> 
      <TextBlock Text="{Binding CategoryName}" /> 
      <TextBlock Text="{Binding CategoryType}" FontSize="7"/> 
     </StackPanel> 
    </DataTemplate> 
</Window.Resources> 

<Grid Margin="0,60"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition/> 
     <ColumnDefinition/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
     <RowDefinition/> 
     <RowDefinition/> 
     <RowDefinition/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 

    <TextBlock Grid.Column="0" Grid.Row="0" Text="Categories" FontWeight="Bold" VerticalAlignment="Center" Margin="20,0"/> 
    <ListBox Name="CategoriesListBox" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Categories}" ItemTemplate="{DynamicResource CategoryModelTemplate}" HorizontalAlignment="left" Margin="20,0,0,0" Grid.RowSpan="4" Width="150" /> 
    <Button Content="Add " HorizontalAlignment="Left" Height="22" Grid.Row="1" VerticalAlignment="Top" Width="129.333" FontSize="9.333" Grid.Column="1" Margin="0,18,0,0"/> 
    <Button Content="Delete selected" HorizontalAlignment="Left" Height="22" Grid.Row="4" VerticalAlignment="Top" Width="129.333" FontSize="9.333" Grid.Column="1" Margin="0,18,0,0"/> 
    <TextBox Name="CategoryField" HorizontalAlignment="Left" Height="22" Grid.Row="2" TextWrapping="Wrap" Text="Category" VerticalAlignment="Top" Width="129.333" FontWeight="ExtraLight" Grid.Column="1" FontSize="9.333"/> 
    <RadioButton Name="CategoryType" Content="Income" HorizontalAlignment="Left" Height="16" Margin="0,24,0,0" Grid.Row="2" VerticalAlignment="Top" Width="71.322" FontSize="9.333" Grid.Column="1" GroupName="CategoryType" IsChecked="True"/> 
    <RadioButton Content="Expense" HorizontalAlignment="Left" Height="16" Margin="76.322,24,0,0" Grid.Row="2" VerticalAlignment="Top" Width="71.322" Grid.Column="1" FontSize="9.333" GroupName="CategoryType"/> 
</Grid> 
</Window> 

модель представление: CategoryViewModel

Public Class CategoryViewModel 
    Inherits BaseViewModel 

    Private _categories As ObservableCollection(Of CategoryModel) 
    Private ReadOnly _unitOfWork As UnitOfWork 

    Public Sub New() 
     _unitOfWork = New UnitOfWork() 
    End Sub 

    Public Sub Init() 
     Dim obscategories = _unitOfWork.GetCategoryRepository().GetAll() 
     Dim observable = New ObservableCollection(Of CategoryModel)() 
     For Each c As Category In obscategories 
      observable.Add(New CategoryModel(c.CategoryName, c.CategoryType)) 
     Next 

     Categories = observable 
    End Sub 

    Public Property Categories As ObservableCollection(Of CategoryModel) 
     Get 
      Return _categories 
     End Get 
     Set(value As ObservableCollection(Of CategoryModel)) 
      _categories = value 
      RaisePropertyChanged("Category") 
     End Set 
    End Property 

    Public Sub AddCategory(categoryName As String, categoryType As Boolean) 
     Dim cat = New CategoryModel(categoryName:=categoryName, categoryType:=categoryType) 
     _categories.Add(cat) 
     _unitOfWork.CategoryRepository.Add(cat.ToCategory()) 
     _unitOfWork.Commit() 
    End Sub 

    Public Sub RemoveCategory(removedIndex As Integer) 
     Dim cat = _categories.ElementAt(removedIndex) 
     Dim entity = _unitOfWork.CategoryRepository.GetById(cat.Id) 
     _unitOfWork.CategoryRepository.Delete(entity) 
     _categories.RemoveAt(removedIndex) 
     _unitOfWork.Commit() 
    End Sub 
End Class 

Я добавил остальную часть кода к следующей: сути Gist code

+1

Try для отладки кода и убедитесь, что в DataContext из ваше представление установлено правильно. Если это работает, посмотрите в окне вывода из своей среды IDE и убедитесь, что ошибок привязки нет. –

ответ

1

Предполагая, что DataContext устанавливается соответствующим образом до CategoryViewModel в Categories собственность вы делаете

RaisePropertyChanged("Category") 

в то время как события должны быть подняты для точного имени свойства

RaisePropertyChanged("Categories") 

поэтому ListBox никогда не уведомила создать новый список

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