【发布时间】:2017-05-04 22:15:46
【问题描述】:
刚开始学习 WPF XAML 中的 DataGrid。这是代码:
型号
Public Class Idea
Public Property IdeaID() As Integer
Public Property Name() As String
End Class
视图模型
Public Class IdeaViewModel
Implements INotifyPropertyChanged
Public Shared Property allIdeas() As New ObservableCollection(Of Idea)
Public Sub New()
For index = 1 To 10
Dim anitem As New Idea
anitem.Name = "Value " & index
allIdeas.Add(anitem)
Next
End Sub
Public ReadOnly Property AddAnItemToList() As ICommand
Get
Return New RelayCommand(AddressOf InsertAnItem)
End Get
End Property
Public Sub InsertAnItem()
Dim anItem As New Idea
anItem.Name = "Item " & allIdeas.Count()
allIdeas.Add(anItem)
End Sub
Public ReadOnly Property ClearTheList() As ICommand
Get
Return New RelayCommand(AddressOf ClearStoredList)
End Get
End Property
Public Sub ClearStoredList()
allIdeas.Clear()
End Sub
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
End Class
查看(仅限 XAML,无代码)
<Window x:Class="IdeaView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:MVVM7"
Title="IdeaView" Height="500" Width="200" WindowStartupLocation="CenterScreen">
<Window.DataContext>
<local:IdeaViewModel/>
</Window.DataContext>
<StackPanel>
<Button Margin="25" Height="50" Content="Insert an item" Command="{Binding AddAnItemToList}"/>
<Button Margin="25" Height="50" Content="Clear stored list" Command="{Binding ClearTheList}"/>
<DataGrid Height="100"
ItemsSource="{Binding allIdeas}"
AutoGenerateColumns="True"
>
</DataGrid>
<DataGrid Height="100"
AutoGenerateColumns="False"
>
<DataGridTextColumn Binding="{Binding allIdeas}"/>
<DataGridTextColumn Binding="{Binding allIdeas}"/>
</DataGrid>
</StackPanel>
</Window>
第一个 DataGrid 很好。第二个 DataGrid 当然不会,因为您不能将列绑定到整个 allIdeas 对象。我只是留下该代码以指出我知道我想要"{Binding Name}"之类的东西,但是我绑定DataGrid的方式不正确并且我无法找到解决这个主题的帖子一个基本的水平。
我正在尝试在 DataGrid 中进行双向绑定,但我想确保我首先了解数据是如何连接的。这就是我尝试手动将 ViewModel 的 ObservableCollection 的属性绑定到 DataGrid 中的列的原因。
【问题讨论】:
-
你想在第二个数据网格中有什么?
-
与第一个自动生成的网格中的内容完全相同,只是我想看看如何在 XAML 代码中手动指定每一列。
-
哦对了。好的。
-
我调整了上面发布的 ViewModel 代码,以便于简单地复制 Model、ViewModel 和 XAML 并立即让它在 WPF 项目中运行。