【发布时间】:2011-11-24 18:27:44
【问题描述】:
我有一个绑定到 Observablecollection 的 Silverlight 列表框,它显示得很好(第一次),但是当我尝试通过后面的代码更新它时,更改不会反映在 UI 中。我使用过 MVVM 模式。请查看并查看视图和视图模型。
<UserControl x:Class="GridOperations.MainPage"
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"
xmlns:local="clr-namespace:GridOperations.ViewModel"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="700">
<UserControl.DataContext>
<local:ShowUserListViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<local:ShowUserListViewModel x:Key="viewModelKey"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<ListBox VerticalAlignment="Top" Margin="0,20,0,0" x:Name="lstBox" ItemsSource="{Binding UserList}" Width="700" Height="150" Background="AliceBlue">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="30,0,0,0" Text="{Binding UserId}" HorizontalAlignment="Left"/>
<TextBlock Margin="30,0,0,0" Text="{Binding Path=UserName, Mode=TwoWay}" Grid.Column="1" HorizontalAlignment="Left"/>
<Button Margin="30,0,0,0" Grid.Column="2" Content="Edit" Height="20" HorizontalAlignment="Left" Command="{Binding Source={StaticResource viewModelKey}, Path=UpdateUserCommand}" />
<Button Margin="10,0,0,0" Grid.Column="3" Content="Del" Height="20" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
public class ShowUserListViewModel : INotifyPropertyChanged
{
public ShowUserListViewModel()
{
mUserList = new ObservableCollection<User>();
mUserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "testuser1", IsAdmin = true });
mUserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "testuser2", IsAdmin = true });
this.UpdateUserCommand = new DelegateCommand(this.UpdateUser);
}
public ICommand UpdateUserCommand { get; private set; }
private ObservableCollection<User> mUserList;
public ObservableCollection<User> UserList
{
get
{
return mUserList;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void UpdateUser()
{
this.UserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "test", IsAdmin = false });
}
}
【问题讨论】:
-
请出示您的 XAML 和代码隐藏。
-
我正在尝试添加。 Stackoverflow 不允许我粘贴代码块而不说“请解释代码场景......”并阻止我添加代码行。
-
你应该把你的代码开始删减,直到它成为能说明你的问题的最小例子。然后更新您的问题。
-
伙计们...我已经采纳了您的建议并将问题范围缩小到绑定了 observablecollection 的列表框(这部分工作正常),有一个按钮来编辑集合,但没有显示在 UI 中.代码中显示和解释的所有内容....任何人都可以在这里提供帮助...
标签: silverlight mvvm listbox observablecollection