Источник изображения в ControlTemplate WPF - PullRequest
1 голос
/ 16 марта 2010

У меня есть ControlTemplate, который предназначен для элемента управления Button, в ControlTemplate у меня есть элемент управления Image, который используется для отображения в кнопке. Теперь я хочу установить источник изображения в кратчайшие сроки, поскольку мне нужно скопировать и вставить ControlTemplate каждая кнопка для установки нового изображения для новой кнопки.

Заранее спасибо.

Ответы [ 4 ]

4 голосов
/ 20 марта 2010
0 голосов
/ 18 ноября 2011
<Button x:Class="FunitureCtlLib.PressedImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="uc"><!--MinHeight="25" MinWidth="50"-->
<Button.Template>
    <ControlTemplate>
        <Grid>
            <Image Name="imgDefault" Source="{Binding Path=DefaultImageSource,ElementName=uc}" Stretch="{Binding Path=ImageStretch,ElementName=uc}"></Image>
            <ContentPresenter Content="{TemplateBinding Property=ContentControl.Content}" />
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="Button.IsPressed" Value="True">
                <Setter Property="Image.Source" TargetName="imgDefault" Value="{Binding Path=PressedImageSource,ElementName=uc}"></Setter>
                <Setter Property="UIElement.Effect">
                    <Setter.Value>
                        <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.6" RenderingBias="Performance" ShadowDepth="0" />
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="Button.IsMouseOver" Value="True">
                <Setter Property="UIElement.Effect">
                    <Setter.Value>
                        <DropShadowEffect BlurRadius="10" Color="White" Direction="0" Opacity="0.6" RenderingBias="Performance" ShadowDepth="0" />
                    </Setter.Value>
                </Setter>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Button.Template>

 /// <summary>
/// ImageButton.xaml 
/// </summary>
public partial class PressedImageButton : Button
{

    #region dependency property

    public static readonly DependencyProperty DefaultImageSourceProperty = DependencyProperty.Register("DefaultImageSource", typeof(ImageSource), typeof(PressedImageButton), new PropertyMetadata(null, new PropertyChangedCallback(DefaultImageSourceChangedCallback)));
    public static readonly DependencyProperty PressedImageSourceProperty = DependencyProperty.Register("PressedImageSource", typeof(ImageSource), typeof(PressedImageButton), new PropertyMetadata(null, new PropertyChangedCallback(PressedImageSourceChangedCallback)));
    public static readonly DependencyProperty ImageStretchProperty = DependencyProperty.Register("ImageStretch", typeof(Stretch), typeof(PressedImageButton), new PropertyMetadata(Stretch.None, new PropertyChangedCallback(ImageStretchChangedCallback)));

    #endregion       

    #region callback

    private static void DefaultImageSourceChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender != null && sender is PressedImageButton)
        {
            PressedImageButton imgbtn = sender as PressedImageButton;
            imgbtn.OnDefaultImageSourceChanged(e.OldValue, e.NewValue);
        }
    }

    private static void PressedImageSourceChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender != null && sender is PressedImageButton)
        {
            PressedImageButton imgbtn = sender as PressedImageButton;
            imgbtn.OnPressedImageSourceChanged(e.OldValue, e.NewValue);
        }
    }

    private static void ImageStretchChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender != null && sender is PressedImageButton)
        {
            PressedImageButton imgbtn = sender as PressedImageButton;
            imgbtn.OnImageStretchChanged(e.OldValue, e.NewValue);
        }
    }

    #endregion

    #region public property

    /// <summary>
    /// 
    /// </summary>
    public ImageSource DefaultImageSource
    {
        get
        {
            return this.GetValue(DefaultImageSourceProperty) as ImageSource;
        }
        set
        {
            this.SetValue(DefaultImageSourceProperty, value);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public ImageSource PressedImageSource
    {
        get
        {
            return this.GetValue(PressedImageSourceProperty) as ImageSource;
        }
        set
        {
            this.SetValue(PressedImageSourceProperty, value);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public Stretch ImageStretch
    {
        get
        {
            return (Stretch)this.GetValue(ImageStretchProperty);
        }
        set
        {
            this.SetValue(ImageStretchProperty, value);
        }
    }       

    #endregion        

    #region protected method

    protected void OnDefaultImageSourceChanged(object oldValue, object newValue)
    {
        //viewmodel.DefaultImageSource = newValue as ImageSource;
        this.DefaultImageSource = newValue as ImageSource;
    }

    protected void OnPressedImageSourceChanged(object oldValue, object newValue)
    {
        //viewmodel.PressedImageSource = newValue as ImageSource;
        this.PressedImageSource = newValue as ImageSource;
    }

    protected void OnImageStretchChanged(object oldValue, object newValue)
    {
        //viewmodel.ImageStretch = (Stretch)newValue;
        this.ImageStretch = (Stretch)newValue;
    }

    #endregion

    #region construct

    public PressedImageButton()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(PressedImageButton_Loaded);
    }

    #endregion

    #region private event

    void PressedImageButton_Loaded(object sender, RoutedEventArgs e)
    {

    }       

    #endregion
}
0 голосов
/ 20 марта 2010

Вы можете получить доступ к элементу из шаблона, используя метод GetTemplateChild(string childName) (с именем вашего элемента, как определено в XAML), например - Если ваше изображение было определено так:

<Image x:Name="MyImage" Stretch="Fill" />

тогда вы бы назвали этот метод следующим образом:

Image myImage = GetTemplateChild("MyImage") as Image;

if (myImage != null)
{
    myImage.Source = "/Images/MyPicture.jpg";
}

Примечание: Вы не сможете использовать этот метод, пока не будет вызван ПОСЛЕ OnApplyTemplate для элемента управления.

0 голосов
/ 16 марта 2010

Вообще говоря, есть два способа установить источник изображения во время выполнения (примеры кода ниже находятся в псевдокоде и не будут компилироваться):

1) В XAML с использованием привязки, где источником привязки будет свойство некоторого объекта, содержащее источник изображения (это сценарий, о котором говорил Слагстер):

Это будет ваш объект:

public class ViewModel
{
  public string ImageURI {get;set;}
}

и будет представлен XAML, где у вас есть кнопка с изображением, а источник изображения установлен посредством привязки:

<Image Source="{Binding Source=ViewModel; Path=ImageURI}"/>

2) Установив источник изображения из кода.

это будет ваш XAML, где у вас есть кнопка с изображением:

<Image x:Name="theImage"/>

и в коде позади вы устанавливаете источник этого изображения:

theImage.Source = new BitmapImage(new Uri("yor image uri"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...