我正在使用MVVM,並有一個視圖讓用戶提交一個消息(如博客),其中列表「保持填充消息張貼」。當他們點擊保存時,這會觸發視圖模型中的保存命令來保存消息。我的問題是,我的列表視圖中的我的gridview不更新。我想知道是否有人能幫助我。我正處於一個剛剛進入圈子的階段。我知道我錯過了一些如果不是很多代碼,但我的腦細胞被炸。從視圖模型更新列表視圖
我的XAML:
<Grid Name="grdMessage" HorizontalAlignment="Left" Width="816">
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Messages" HorizontalAlignment="Left" VerticalAlignment="Bottom" />
<ListView Name="lstMessage" Grid.Row="2" HorizontalAlignment="Left" VerticalAlignment="Bottom"
Width="762" Height="auto" Margin="15,0,0,0" ItemsSource="{Binding Path=MessageList}">
<ListView.View>
<GridView>
<GridViewColumn Width="462" Header="Message">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Message, Mode=TwoWay}" TextAlignment="Left" HorizontalAlignment="Left" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="150" Header="Submitter">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Submitter, Mode=TwoWay}" TextAlignment="Left" HorizontalAlignment="Left" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<TextBox Name="txtNewMessage" Grid.Row="4" Grid.Column="0"
HorizontalAlignment="Left" VerticalAlignment="Top"
Width="762" Height="auto" TextWrapping="Wrap"
AcceptsReturn="True" HorizontalScrollBarVisibility="Auto"
Visibility="Collapsed" Text="{Binding Path=Message, Mode=TwoWay}"/>
<Button Name="btnAddMessage" Grid.Row="6" Grid.Column="0" Content="Add" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,0,0" Command="{Binding Path=Save}" />
我的視圖模型:
Message message;
ObservableCollection<Message> messageList;
RelayCommand save;
public ObservableCollection<Message> MessageList
{
get
{
if (messageList == null)
messageList = new ObservableCollection<Message>();
}
}
public ICommand Save
{
get
{
return saveCmd ?? (save = new RelayCommand(parameter => SaveMessage()));
}
}
void SaveMessage()
{
this.MessageList.Add(this.Message); dataSource.AddMessage(message);視圖模型的
}
Message Model
string message;
[DataMember]
public int Submitter {get; set;}
[DataMember]
public string Message
{
get{ return(message);}
set
{
if (message != value)
{
message = value;
OnPropertyChanged("Message");
}
}
}
它在代碼裏有點像messageList.add(myNewMessage); ? – Klaus78
您正在添加到數據庫,但是您是否更新messageList? – Dabblernl