【问题标题】:Relative Path not resolved in Template Binding WPF模板绑定 WPF 中未解析的相对路径
【发布时间】:2013-10-28 19:03:40
【问题描述】:

我正在尝试在 WPF 中创建一个图像按钮。我所做的是

  1. 创建一个继承自 Button 的用户控件,并在其中声明一个依赖属性,该属性应该具有所需的图像。
  2. 在资源字典中为其声明 xaml 模板。
  3. 将相对路径和完整路径传递给该依赖项属性,完整路径有效,但相对路径无效。

用户控制类

  public class ButtonWithImage : Button
{

    public ImageSource ButtonImage
    {
        get { return (ImageSource)GetValue(ButtonImageProperty); }
        set { SetValue(ButtonImageProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ButtonImage.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ButtonImageProperty =
        DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ButtonWithImage));


}

资源字典代码

    <Style x:Key="ButtonWithImageStyle" TargetType="complaintRegister:ButtonWithImage">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="complaintRegister:ButtonWithImage">
                <StackPanel>
                    <Image Source="{Binding ButtonImage, RelativeSource={RelativeSource TemplatedParent}}" Width="50" Height="50"/>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

XAML

  <complaintRegister:ButtonWithImage x:Name="ButtonAdd" Content="Add New Complaint" Style="{StaticResource ButtonWithImageStyle}"
                                           ButtonImage="Resources\Plus.png"
                                           Width="150" Height="75" Margin="10 0" Command="{Binding NewCommand}">

        </complaintRegister:ButtonWithImage>

错误

它确实在设计模式下显示图像,但在运行时抛出此异常

Cannot locate resource 'resources/plus.png'

我不禁认为它正在尝试解析“resources/plus.png”而不是“Resources/Plus.png”。

【问题讨论】:

    标签: wpf xaml dependency-properties templatebinding


    【解决方案1】:

    我敢打赌,输出窗口中会显示绑定错误。 :)

    您如何在此处向我们发布该错误消息。

    顺便说一句,在这种情况下,使用 TemplateBinding 而不是 RelativeSource TemplatedParent 更合适。

    TemplateBinding 可以这样说,指定在控件的模板中运行良好。 :)

    查看这些链接:

    http://msdn.microsoft.com/en-us/library/ms742882(v=vs.110).aspx

    http://www.codeproject.com/Tips/599954/WPF-TemplateBinding-with-ControlTemplate

    编辑:

    啊,你在谈论图像的位置。

    默认情况下,Image 控件仅在使用 XAML 指定其 Source 属性时识别已编译的资源图像。但是,我们可以使用转换器或自定义标记扩展来实现这一目标。以下链接包含有关数据绑定转换器和标记扩展的信息。

    因此将 png 设置为构建操作 -> 资源并重新构建您的解决方案或使用它:

    <Image>
        <Image.Source>
            <BitmapImage UriSource="../Relative/Path/To/Image.png" />
        </Image.Source>
    </Image>
    

    如果您希望在此使用 MVVM 并根据数据更改路径,我建议您使用绑定:

    <Image Source="{Binding MyPath}" Height="50"... />
    

    【讨论】:

    • 我已经更新了我的问题中的错误,请仔细阅读。它永远不会运行,但会给出异常。
    • 您好,您说的是图像位置。请阅读我的编辑。
    猜你喜欢
    • 2014-10-20
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多