Updating listbox data with RaisePropertyChanged
In my silverlight app i have a view with a listbox:
<ListBox Canvas.Left="12" Canvas.Top="72" Height="468" Name="invoiceList" Width="453" ItemsSource="{Binding ElementList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
which is bound to the list of elements in my VM. The problem is that when I add new elements, one by one, using Relay Command:
public RelayCommand<Element> AddNewElement = new RelayCommand<Element>(NewElement(element));
public void NewElement(Element element)
{
if(ElementList == null) ElementList = new List<Element>();
if (element != null) ElementList.Add(element);
RaisePropertyChanged("ElementList");
}
the listbox updates only once, i.e. it shows only开发者_如何学C first element of the collection , though more items are inside ElementList
You need to bind to a list of type ObservableCollection then every update to the list collection will trigger the binding to update.
Example on how to create an observable collection of your list:
public ObservableCollection<string> MyElements { get; set; }
public void FillList()
{
List<string> testList = new List<string>() {"string1", "string2"};
MyElements = new ObservableCollection<string>(testList);
}
MyElements.Add("string3")
will trigger binding to update
EDIT: I added a working example, I provide the xaml and ViewModelCode with the use of acommand to add some strings:
xaml:
<ListBox ItemsSource="{Binding MyStrings}" />
<Button Command="{Binding AddExtraStringCommand}" Content="Add ExtraString" />
viewmodel.cs
public class Window1ViewModel : ViewModelBase
{
public ObservableCollection<string> MyStrings { get; set; }
public RelayCommand AddExtraStringCommand { get; set; }
public Window1ViewModel()
{
patient = new Patient() { BirthdayString = "21/11" };
MyStrings = new ObservableCollection<string>() { "string1", "string2", "string3" };
AddExtraStringCommand = new RelayCommand(AddExtraString);
}
public void AddExtraString()
{
MyStrings.Add("nog enen extra om: " + DateTime.Now);
}
}
I don't have to trigger the RaisePropertyChanged to make it work. Maybe you can check your code to this code example.
精彩评论