簡體   English   中英

將圖像源綁定到字符串

[英]Bind Image source to string

我在表格中使用了一個顯示圖像的列:

<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"它會將圖像顯示為資源。 我怎樣才能做到這一點?

您將不得不使用基於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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM