簡體   English   中英

WPF動態創建的列表框未刷新

[英]WPF A dynamic created ListBox is not being refreshed

我有問題,下面的代碼工作正常,它使用某些項目創建了一個新的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; }
    }

使用ObservableCollection<string>而不是List<string> ObservableCollection<T>實現INotifyCollectionChanged接口,允許它通知綁定已添加新項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM