如果在另一个类中填充了字典,如何正确实现 IValueConverter?
我确定我在这里做错了,但是为了正确解释我的问题,这里是支持该问题的代码。
iPresenter_IconLists.cs
public interface iPresenter_IconLists
{
Dictionary<string, IconPositionDetails> IconDetails { get; set; }
}
Presenter_IconLists.cs
public class Presenter_IconLists : iPresenter_IconLists, IValueConverter
{
public Presenter_IconLists()
{
}
public void PopulateDictionaryTest()
{
this.IconDetails.Add("test1", new IconPositionDetails()
{
x = 0,
y = 0
});
this.IconDetails.Add("test2", new IconPositionDetails()
{
x = 0,
y = 0
});
this.IconDetails.Add("test3", new IconPositionDetails()
{
x = 0,
y = 0
});
}
Dictionary<string, IconPositionDetails> _IconDetails = new Dictionary<string, IconPositionDetails>();
public Dictionary<string, IconPositionDetails> IconDetails
{
get { return this._IconDetails; }
set { this._IconDetails = value; }
}
// IValueConverter implementation
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
iPresenter_IconLists i = this;
IconPositionDetails ipd = i.IconDetails[value.ToString()];
// or
// IconPositionDetails ipd = this.IconDetails[value.ToString()];
return string.Format("x: {0}, y: {1}", ipd.x, ipd.y);
}
}
主窗口.xaml
<Window.Resources>
<l:Presenter_IconLists x:Key="DictConvert" x:Name="DictConvert" />
<TextBlock Text="{Binding Converter={StaticResource DictConvert}, ConverterParameter=Value.x}" Height="28" HorizontalAlignment="Left" Margin="60,49,0,0" VerticalAlignment="Top" FontSize="11" />
</Window.Resources>
主窗口.xaml.cs
Presenter_IconLists iconlists;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
this.iconlists = new Presenter_IconLists();
this.iconlists.PopulateDictionaryTest();
lbIcons.ItemsSource = this.iconlists.IconDetails;
}
这里的问题是,我总是得到“字典中不存在给定的键”。当我检查 this.IconDetails 集合的数量时,它为零。
如何在 Converter 中访问我的字典?