1

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」を解決しようとしていると思わざるを得ません。

4

1 に答える 1

3

出力ウィンドウにバインディング エラーが表示されるはずです。:)

そのエラー メッセージをここに投稿してください。

ところで、そのような場合は、RelativeSource TemplatedParent の代わりに TemplateBinding を使用する方が適切です。

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 を build action -> resource に設定し、ソリューションを再構築するか、これを使用します。

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

これでMVVMを使用し、データに基づいてパスを変更したい場合は、バインディングを使用することをお勧めします:

<Image Source="{Binding MyPath}" Height="50"... />
于 2013-10-28T19:13:00.320 に答える