【发布时间】:2017-12-12 19:25:49
【问题描述】:
我正在尝试使用我的数据库中的项目列表填充页面。我已经为这些项目创建了模型和视图模型,但它们没有显示在我的 ItemsControl 中。
我有一个模型,它有一个相应的实现 INotifyPropertyChanged 的 ViewModel。
型号:
Public Class ItemModel
Private _year As String
Public Property Year As String
Get
Return _year
End Get
Set(value As String)
_year = value
End Set
End Property
Public Sub New()
_year = Now.Year & "-" & (Now.Year + 1)
End Sub
Public Function ToString() As String
Return _year & " Item Model"
End Function
End Class
视图模型:
Imports System.ComponentModel
Public Class ItemViewModel
Implements INotifyPropertyChanged
Private _currentItem As ItemModel
Public Property CurrentItem As ItemModel
Get
Return _currentItem
End Get
Set(value As ItemModel)
If _currentItem IsNot value Then
_currentItem = value
NotifyPropertyChanged("CurrentItem")
End If
End Set
End Property
Public Sub New()
_currentItem = New DciSurveyModel()
End Sub
Public Function ToString() As String
Return _currentItem.Year & " Item ViewModel"
End Function
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
我将 ItemsControl 绑定到 ViewModel 的 ObservableCollection,但 ViewModel 没有出现。我尝试使用 ItemsTemplate 创建一个文本框,将 Text={Binding Path=CurrentItem.Year} 设置为无济于事。
XAML:
<Page x:Class="ItemPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Name="ItemPage"
Title="ItemPage" Loaded="Page_Loaded_1" Margin="10">
<Grid>
<ItemsControl ItemsSource="{Binding Path=ItemCollection}" />
</Grid>
</Page>
下面是代码:
Imports OClient = Oracle.DataAccess.Client
Imports System.Collections.ObjectModel
Imports System.Data
Class ItemPage
Private ds As DataSet
Private itemsTable As DataTable
Public Property ItemsCollection As ObservableCollection(Of ItemViewModel)
Private Sub Page_Loaded_1(sender As Object, e As RoutedEventArgs)
Dim itemsQry = "select item_year from items order by item_year desc"
Dim queryCmd As New OClient.OracleCommand(itemsQry, O.con)
Dim adapter As New OClient.OracleDataAdapter(queryCmd)
ds = New DataSet
adapter.Fill(ds, "items")
itemsTable = ds.Tables("items")
ItemsCollection = New ObservableCollection(Of ItemViewModel)
For Each r As DataRow In surveys.Rows
Dim newItem As New ItemViewModel
newItem.CurrentItem.Year = r.Item("ITEM_YEAR").ToString
Next
Me.DataContext = Me
End Sub
End Class
我很难弄清楚我的应用程序在哪里崩溃了。它在我的 ViewModel 实现中吗?我没有正确绑定数据吗?我需要对我的 ObservableCollection 做一些不同的事情吗?
感谢您帮助新手。
【问题讨论】: