【发布时间】:2011-10-13 06:28:35
【问题描述】:
我有问题,下面的代码工作正常,它创建了一个包含一些项目的新列表框控件。但是,当我想更改它的一些项目(例如,将新项目添加到 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; }
}
【问题讨论】:
-
除了对 GetValue 和 SetValue 的调用之外,依赖属性的 CLR 包装器中绝对应该没有任何内容。 DepedencyProperties 有自己的更改通知,如果属性发生更改,CLR-setter 代码不一定会被调用(这就是为什么那里应该没有任何内容的原因)。此外,元数据应初始化为
null,否则所有 DataItems 共享相同的集合实例,如果未设置,则在 ctor 中创建一个实例,如果您希望它初始化。可能想看看overview。
标签: c# wpf xaml data-binding listbox