WPF 使用具有绑定对象属性的 IValueConverter 创建对象



我在XAML中用于绑定的对象只能具有字符串属性。但在装订方面,我需要其他类型。我想我使用IValueConverter中的Converter函数,在这里我将从字符串属性创建对象并返回它。一个字符串属性将为空,在绑定中,我将从Converter方法返回另一个对象。我尝试过这个方法,但在Convert方法中,ObservableCollection中的主要对象为null。这是我的XAML

<Maps:MapItemsControl ItemsSource="{Binding}">
            <Maps:MapItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel  Orientation="Horizontal" Background="Transparent" Tapped="ItemStckPanel">
                        <Image Source="/Assets/pushpin.gif" Height="30" Width="30" 
                               Maps:MapControl.Location="{Binding Location, 
                            Converter={StaticResource StringToGeopoint}}" 
                                Maps:MapControl.NormalizedAnchorPoint="0.5,0.5"/>
                        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5">
                            <TextBlock FontSize="20" Foreground="Black" Text="{Binding Name}"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </Maps:MapItemsControl.ItemTemplate>
        </Maps:MapItemsControl>

这是我的转换方法:

public object Convert(object value, Type targetType, object parameter, string language)
    {
        Event _event = (Event) parameter;
        BasicGeoposition position = new BasicGeoposition();
        position.Latitude = _event.Latitude;
        position.Longitude = _event.Longitude;
        return new Geopoint(position);
    }

我想在Converter方法中传递我的实际父对象。解决方案是更改

Maps:MapControl.Location="{Binding Location, 
                        Converter={StaticResource StringToGeopoint}}" 

Maps:MapControl.Location="{Binding Converter={StaticResource StringToGeopoint}}" 

它的工作原理是:)

绑定对象被馈送到Convert()-方法的"value"参数中。

您正在访问与相对应的参数

<... ConverterParameter= .../>

它没有设置在您的xaml中。

实际上,你必须这样写你的Convert()-方法:

public object Convert(object value, Type targetType, object parameter, string language)
{
    Event _event = (Event) value;
    BasicGeoposition position = new BasicGeoposition();
    position.Latitude = _event.Latitude;
    position.Longitude = _event.Longitude;
    return new Geopoint(position);
}

/更新:

Maps:MapItemControl上的ItemsSource={Binding}绑定到父对象的DataContext。这应该是您的ObservableCollection。

在ItemTemplate中,您的图像有一个"Location"-属性,该属性绑定到ObservableCollection中每个项目的"Location"属性。你也可以写:

{Binding Path=Location, Converter={StaticResource StringToGeopoint}}

现在,在该绑定被完全评估之前,存储在Location属性中的Object被传递到转换器,然后结果被传递到Image上的"Location"-属性。

如果要将null对象传递给"value"-参数,则意味着原始Binding将null值传递给Converter,原因可能是源对象上的Property为null,也可能是该属性不存在。

最新更新