基于内容动态设置XAML图像来源

4

嗯,它并不是真正的动态的,至少在运行时不会改变。

我的想法是有几个按钮,每个按钮都有一个独特的图像(32x32的图标)。所有按钮共享一种样式,我在ControlTemplate中进行了修改。因此,每个图像也有两种颜色,一种是正常的,另一种是鼠标悬停时的颜色。

我注意到当我声明图像的源路径时,它们几乎都是相同的,所以我想DRY(不要重复自己)。如果我可以使用按钮名称或其他属性作为源路径的一部分(即图像文件的名称),那就是好的编程。

问题是我对XAML、WPF和可能的编程都很陌生,所以我不知道该怎么做。我想这需要代码后台或某种转换器(我猜我会再多读一些关于转换器的资料)。这里有一点代码(这不起作用,但它给你一个大致的想法(希望如此)):

<Style x:Key="ButtonPanelBigButton" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Name="ButtonBorder"
                        Height="78"
                        MaxWidth="70"
                        MinWidth="50"
                        BorderThickness="0.5"
                        BorderBrush="Transparent"
                        CornerRadius="8" >
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="2*" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>

                        <!-- Here I wan't to put in the Name property of the button because there is a picture there to match -->
                        <Image x:Name="ButtonIcon" Source="..\Images\Icons\32x32\Blue\{Binding Name}.png" 

                               Margin="4"
                               Height="32"
                               Width="32"
                               HorizontalAlignment="Center" 
                               VerticalAlignment="Center" />

                        <TextBlock Grid.Row="1"
                                   Padding="5,2,5,2"
                                   TextWrapping="Wrap"
                                   Style="{StaticResource MenuText}"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center">
                            <ContentPresenter ContentSource="Content" />                
                        </TextBlock>
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True" >
                        <Setter TargetName="ButtonIcon" Property="Source" Value="..\Images\Icons\32x32\Green\user.png" /> <!-- Same Here -->
                        <Setter TargetName="ButtonBorder" Property="BorderBrush" Value="{StaticResource SecondColorBrush}" />
                        <Setter TargetName="ButtonBorder" Property="Background">
                            <Setter.Value>
                                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1" Opacity="0.5">
                                    <GradientStop Color="{StaticResource MainColor}" Offset="1" />
                                    <GradientStop Color="{StaticResource SecondColor}" Offset="0.5" />
                                    <GradientStop Color="{StaticResource MainColor}" Offset="0" />
                                </LinearGradientBrush>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </ControlTemplate.Triggers>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

希望你能理解我的意思,帮助我将代码变得更加简洁(我现在又在重复自己!)。
2个回答

2

没错,解决这个问题的简单方法是使用转换器。

源属性需要一个ImageSource,所以你需要在你的转换器中自行加载位图。

这个转换器可以像这样使用:

 <Image Source="{Binding Name,
                         RelativeSource={RelativeSource TemplatedParent},
                         Converter={x:Static local:ImageSourceLoader.Instance},
                         ConverterParameter=..\Images\Icons\32x32\Blue\{0}.png}" />

实现方式如下:

public class ImageSourceLoader : IValueConverter
{
  public static ImageSourceLoader Instance = new ImageSourceLoader();

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var path = string.Format((string)parameter, value.ToString());
    return BitmapFrame.Create(new Uri(path, UriKind.RelativeOrAbsolute));
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

请注意,这种简单的解决方案无法处理相对Uri,因为Image的BaseUri属性在转换器中不可用。如果您想使用相对Uri,可以通过绑定附加属性并使用StringFormat来实现:
 <Image local:ImageHelper.SourcePath="{Binding Name,
                         RelativeSource={RelativeSource TemplatedParent},
                         StringFormat=..\Images\Icons\32x32\Blue\{0}.png}" />

附加属性的 PropertyChangedCallback 处理程序在将 BaseUri 与格式化的 Uri 字符串组合后加载图像:

public class ImageHelper : DependencyObject
{
  public static string GetSourcePath(DependencyObject obj) { return (string)obj.GetValue(SourcePathProperty); }
  public static void SetSourcePath(DependencyObject obj, string value) { obj.SetValue(SourcePathProperty, value); }
  public static readonly DependencyProperty SourcePathProperty = DependencyProperty.RegisterAttached("SourcePath", typeof(string), typeof(ImageHelper), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) =>
      {
        ((Image)obj).Source =
          BitmapFrame.Create(new Uri(((IUriContext)obj).BaseUri, (string)e.NewValue));
      }
  });
}

好的,我正在尝试让它工作,但由于路径和{0},字符串字面量和标记扩展存在问题。 - Ingó Vals
OK运行得很好,只需更改一个属性,因为像这样的文字格式={ }..\Images\Icons\32x32\Green\{0}.png}"。 - Ingó Vals

0
你可以使用标签属性并在标签中设置图像的完整路径,然后使用它。 以下是我的代码,更加清晰明了。
*<Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="#373737" />
            <Setter Property="Foreground" Value="White" />  
           <Setter Property="FontSize" Value="12" />
            <Setter Property="SnapsToDevicePixels" Value="True" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border CornerRadius="7" Background="{TemplateBinding Background}" FlowDirection="RightToLeft">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="50"/>
                                    <ColumnDefinition Width="2"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Image x:Name="imgDistance"  Source="{Binding Tag,RelativeSource={RelativeSource TemplatedParent}}"
          
                             Width="35" Height="35" HorizontalAlignment="Left" Margin="42,7,0,8" Grid.Column="0"/>*

然后我将它用在按钮中,如下所示

<Button x:Name="btnDistance" Height="50" VerticalAlignment="Top" Margin="0,4,0,0" Curs

or="Hand" Click="btnDistance_Click" Tag="/Images/distance.png">

    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接