WPF A dynamic created ListBox is not being refreshed
I have problem, the code below works fine, it creates a new Listbox control with some items. BUT, when I want to change some of its items (e.g ad new items to the Title
property) the ListBox is not being refreshed. Why ?
XAML
<DataTemplate x:Key="myRes">
<Grid Background="White" Height="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Width="15" Height="18" Source="D:\separator.png"></Image>
<ListBox VerticalAlignment="Top" SelectionChanged="ListBox_SelectionChanged" Width="200" Height="300" Grid.Column="1" ItemsSource="{Binding Title}" />
</Grid>
</DataTemplate>
<ItemsControl VerticalAlignment="Top" Margin="5 0 0 0" Height="350" Grid.Column="1" Grid.Row="0"
ItemsSource="{Binding ElementName=mainWindow, Path=DataItems}"
ItemTemplate="{StaticResource myRes}">
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
.CS
public class MyDataItem : DependencyObject, INotifyPropertyChanged
{
private void NotifyProp开发者_如何转开发ertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public List<string> Title
{
get
{
return GetValue(TitleProperty) as List<string>;
}
set
{
SetValue(TitleProperty, value);
NotifyPropertyChanged("Title");
}
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(List<string>), typeof(MyDataItem), new UIPropertyMetadata(new List<string>()));
}
private ObservableCollection<MyDataItem> dataItems;
public ObservableCollection<MyDataItem> DataItems
{
get { return dataItems; }
}
Use an ObservableCollection<string>
instead of a List<string>
. ObservableCollection<T>
implements the INotifyCollectionChanged
interface, allowing it to notify the binding that a new item has been added.
精彩评论