1

如果在另一个类中填充了字典,如何正确实现 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 中访问我的字典?

4

2 回答 2

0

您在绑定中使用转换器参数而不是路径。

在绑定中使用路径:

<DataTemplate x:Key="lbItems" x:Name="lbItems">
    <TextBlock Text="{Binding Path=Value.name, Converter={StaticResource DictConvert}}" />
</DataTemplate>

或在Convert函数中使用参数

IconPositionDetails ipd = i.IconDetails[parameter.ToString()];
于 2012-09-07T17:24:33.340 回答
0

您的构造函数不会将项目添加到字典中,因此其中没有项目。当你去转换时,字典是空的。

在某些时候,您需要用值填充字典。这不会发生,因为字典是由 WPF ( <l:Presenter_IconLists x:Key="DictConvert" />) 创建的,并且从未向其中添加值。

于 2012-09-07T16:47:19.260 回答