将图像源绑定到字符串

时间:2017-06-23 17:13:44

标签: c# wpf data-binding

我在表格中使用了一个显示图像的列:

<DataGrid ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Fill" Width="1*" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding fill}" Width="15px" Height="15px"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    <DataGrid.Columns>
</DataGrid>

C#:

// CustomRow contains a public member called fill
public List<CustomRow> tableList;
//...
this.table.ItemsSource = this.tableList;

我决定使用资源会更好。所以我的计划是将图像源绑定到资源。我创建了一个测试资源:

<Window.Resources>
    <BitmapImage x:Key="test-icon" UriSource="Resources/testicon.png" />
</Window.Resources>

我想将fill绑定到图像源,因此当fill = "test-icon"它将图像显示为资源时。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您必须使用基于source属性值查找资源的转换器:

public class ResourceConverter : DependencyObject, IValueConverter
{
    public static readonly DependencyProperty ParentWindowProperty =
         DependencyProperty.Register("ParentWindow", typeof(Window), typeof(ResourceConverter));

    public Window ParentWindow
    {
        get { return (Window)GetValue(ParentWindowProperty); }
        set { SetValue(ParentWindowProperty, value); }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string resourceKey = value as string;
        if (ParentWindow == null || resourceKey == null)
            return value;

        return ParentWindow.Resources[resourceKey];

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
<Window ... x:Name="win>
    <Window.Resources>
        <BitmapImage x:Key="test-icon" UriSource="Resources/testicon.png" />
    </Window.Resources>
...
<DataGrid ItemsSource="{Binding}">
    <DataGrid.Resources>
        <local:ResourceConverter x:Key="ResourceConverter"
                                 ParentWindow="{Binding Source={x:Reference win}}" />
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Fill" Width="1*" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding Path=fill, Converter={StaticResource ResourceConverter}}"
                                   Width="15px" Height="15px"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>