【问题标题】:Find the userControl in which the image is from Converter找到图片来自 Converter 的 userControl
【发布时间】:2014-08-30 09:29:14
【问题描述】:

我有一个实现 IValueConverter 接口的转换器。这是转换方法:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Concat(@"..\Images\myFolder\", System.Convert.ToString(value), ".png");
    }

在我的 xaml 代码中,在资源中:

<converters:ImageSourceConverter x:Key="ImageSourceConverter"/>

我是这样使用它的:

<Image Source="{Binding Path=myCategoryId, Converter={StaticResource ImageSourceConverter}}" Width="150" Height="150"></Image>

我遇到的问题是:我的解决方案中有几个带有图像的文件夹。图片的路径是这个:

..\Images\myFolder\1.png
..\Images\myFolderJohn\2.png
..\Images\myFolderJack\3.png

其中文件名是一个 id。 我在 Convert 方法中的代码仅适用于 myFolder 中的图像。文件夹的名称取决于放置图像的用户控件。所以,应该是这样的:

if (userControl == "John")
    return String.Concat(@"..\Images\myFolderJohn\", System.Convert.ToString(value), ".png");
if (userControl == "Jack")
    return String.Concat(@"..\Images\myFolderJack\", System.Convert.ToString(value), ".png");

我如何知道在 Convert 方法中显示图像的用户控件?

【问题讨论】:

  • 这是带有多值转换器的MultiBinding 的典型用例。参见例如this answer 了解一些细节。

标签: wpf mvvm converter ivalueconverter


【解决方案1】:

在绑定中使用ConverterParameter

John UseControl 中的 xaml 将是,

<Image Source="{Binding Path=RentalTypeId, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Converter={StaticResource ConvImageSource}, ConverterParameter=John}"/>

在你的转换器类中使用这样的参数,

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return String.Concat(@"..\Images\myFolder", System.Convert.ToString(parameter), "\\", System.Convert.ToString(value), ".png");
}

【讨论】:

    【解决方案2】:

    您可以使用转换器参数,如下所示:

    在“John”用户控件中:

    <Image Source="{Binding Path=myCategoryId, Converter={StaticResource ImageSourceConverter}, ConverterParameter=John}" Width="150" Height="150"></Image>
    

    在“Jack”用户控件中:

    <Image Source="{Binding Path=myCategoryId, Converter={StaticResource ImageSourceConverter}, ConverterParameter=Jack}" Width="150" Height="150"></Image>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多