c# - WPF 图像源绑定(bind)有时有效有时无效

标签 c# wpf xaml binding

我在尝试绑定(bind)图像源时遇到了一些问题。我正在创建一个棋盘游戏,您可以在其中选择一个玩家来查看其属性(包括他的图像)。板上的字段也有图像作为背景。

我为字段创建的模板:

<ControlTemplate x:Key="fieldButtonTemplate" x:Name="fieldButtonTemplateName" TargetType="{x:Type Button}">
    <Grid x:Name="fieldGrid" Visibility="Visible">
        <Grid.LayoutTransform>
            <RotateTransform Angle="{Binding ImageRotate}" />
        </Grid.LayoutTransform>
        <Grid.Background>
            <ImageBrush ImageSource="{Binding Path=ImageSource}"/>
        </Grid.Background>
        <Grid.RowDefinitions>
            ....
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          ...
        </Grid.ColumnDefinitions>
    </Grid>
</ControlTemplate>

还有一个用于查看玩家属性的:

<Image Source="{Binding Path=CurrentlySelected.ImageSource}" Grid.Column="0" Grid.Row="0"
                   Grid.ColumnSpan="2"  Stretch="Fill" />
<StackPanel x:Name="CurrentPlayerStackPanel"  Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2">
      <TextBlock Text="{Binding Path=CurrentlySelected.Name}" TextWrapping="Wrap"
                           FontFamily="Magneto" FontSize="20" Foreground="BlanchedAlmond"/>
      <TextBlock Text="{Binding Path=CurrentlySelected.Character}" TextWrapping="Wrap"
                           FontFamily="Magneto" FontSize="20" Foreground="BlanchedAlmond"/>
      <TextBlock Text="{Binding Path=CurrentlySelected.Money}" TextWrapping="Wrap"
                           FontFamily="Magneto" FontSize="20" Foreground="BlanchedAlmond"/>
</StackPanel>

问题是图像仅在选择玩家时显示,并且不显示为网格的背景。 我为玩家和 field 创建了一个界面:

interface IVisualObject
{
    int ImageRotate { get; set; }
    string ImageSource { get; set; }
}

图像是资源,构建操作设置为内容,复制到输出目录设置为复制(如果较新)。我试图作为图像源传递的字符串就像

"pack://siteoforigin:,,,/Resources/picture.jpg"

btw ImageRotate 绑定(bind)得很好。 提前致谢!

编辑: 如果我将其设置为

<Grid.Background>
     <ImageBrush ImageSource="pack://siteoforigin:,,,/Resources/picture.jpg"/>
</Grid.Background>

它有效。

最佳答案

将您的属性设置为 ImageSource 而不是字符串,或者使用此答案中提到的转换器:Binding image source through property in wpf 。当您对字符串进行硬编码时,xaml 编译器会为您执行此操作,这就是它起作用的原因。

关于c# - WPF 图像源绑定(bind)有时有效有时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35816919/

相关文章:

c# - Telerik RadComboBox 应用 SelectionBoxTemplate OnLoad?

wpf - 附加属性在 WPF 中究竟是如何工作的?

c# - 与 RazorEngine 同时发送电子邮件时出错

asp.net - 无法摆脱 "Login failed for user IIS APPPOOL\NETWORKSERVICE"

WPF:仅对直接子项设置样式

.net - 为什么在绑定(bind)到它时没有设置我的依赖属性?

c# - 参数 : (required, optional) vs (required, required, optional)

c# - 我们需要同时使用 ADODB 和 OLEDB 吗?

c# - 将一对值与值对数组进行比较 C#

wpf - 将可见性绑定(bind)到 Text.Length