我有一个在包含自定义类的用户控件中创建的 ObservableCollection。自定义类包含一些字符串和布尔值,没什么特别的。
public class StringLineInfo : INotifyPropertyChanged
{
private string name { set; get; }
private Color color { set; get; }
private bool visible { set; get; }
private bool follow { set; get; }
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged("Name");
}
}
public Color Color
{
get { return color; }
set
{
color = value;
NotifyPropertyChanged("Color");
}
}
public bool Visible
{
get { return visible; }
set
{
visible = value;
NotifyPropertyChanged("Visible");
}
}
public bool Follow
{
get { return follow; }
set
{
follow = value;
NotifyPropertyChanged("Follow");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
在自定义控件的 Xaml 中,我添加了自定义图例控件。在自定义图例中,我有另一个 ObservableCollection,ItemsControl 是数据绑定到的。
在 legend.xaml 中:
<!--<Image Name="imgMyImage" Grid.Column="1" Height="30" Width="30" Margin="5" Source="{Binding Name, Converter=NameToSrcConverter, ConverterParameter={StaticResource IconDictionary}}" />-->
<TextBlock Name="txtlineName" FontSize="12" Foreground="Black" Text="{Binding Converter={StaticResource nameConverter}}" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="2"/>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在 legend.xaml.cs 中:
public ObservableCollection<StringLineInfo> allLines = new ObservableCollection<StringLineInfo>();
public Dictionary<string, string> DvrIconDictionary = new Dictionary<string, string>();
public Legend()
{
InitializeComponent();
DataContext = this;
itmCtrol.ItemsSource = allLines;
}
// to set the ItemsSource
public void setItemsSource(ObservableCollection<StringLineInfo> source)
{
if (itmCtrl.ItemsSource == null)
{
itmCtrl.ItemsSource = source;
}
}
在主用户控件的构造函数中,我将图例中的 ObservableCollection 设置为等于主用户控件中的 ObservableCollection。
public MainControl()
{
InitializeComponent();
MapLegend.SizeChanged += new SizeChangedEventHandler(MapLegend_SizeChanged);
MapLegend.allLines = this.allLines;
}
即使两个 ObservableCollections 始终包含相同的数据(它们现在是同一个对象),ItemsControl 也不会更新或显示任何内容。但是,如果我稍后在代码中将 ObservableCollections 设置为相等,比如单击按钮,那么它就可以正常工作。
该按钮只调用“setItemsSource”函数。
关于为什么我不能在启动时将它们设置为相等的任何想法?