WPF动态创建的ListBox未刷新

时间:2011-07-26 09:33:36

标签: c# wpf xaml data-binding listbox

我有问题,下面的代码工作正常,它会创建一个包含一些项目的新Listbox控件。但是,当我想更改其某些项目(例如将新项目添加到Title属性)时,ListBox不会被刷新。为什么?

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 NotifyPropertyChanged(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; }
    }

1 个答案:

答案 0 :(得分:3)

使用ObservableCollection<string>代替List<string>ObservableCollection<T>实现INotifyCollectionChanged接口,允许它通知绑定已添加新项目。