How to change an image in Runtime with WPF

Asked

Viewed 172 times

4

I have an item that should change the images as an old value check and new value is happening. I have a part of the codes ready and the images of Static Resources. But, I am locked on how to proceed from here

I have this code that indicates the difference in values.

public enum Deviation
        {
            None = 0,
            Up = 1,
            Down = 2
        }

 public bool ShowDifference { get; set; }

 public double ShouldShowDifference
            {
                get => // colocar a chamada de verificação e determinação de imagem com o metodo de ValorAlterado

                set => _showDifference = value;
            }
public Deviation ValorAlterado
            {
                get
                {
                    if (Value == ValorAnterior)
                        return Deviation.None;

                    return Value > ValorAnterior? Deviation.Up : Deviation.Down;
                }
            }

            double ValorAnterior{ get; set; } = double.NaN;

            public double Value
            {
                get => _value;
                set
                {
                    this.ValorAnterior = _value;
                    _value = value;
                }
            }

And I need this indication to go to this shampooing, stating that for the deviation condition with UP the Static Resource must be Icons.Buttons.Up and for DOWN it must be Icons.Buttons.Down

<Image Source="{StaticResource Icons.Buttons.Down}" Height="20"  Width="20"/>

I’m still developing how to form the bindings and the like, so I’m a little lost on how to join these parts that I developed with the overall goal.

---------- UPDATE AFTER BRUNO’S REPLY

Code I did, when debugging works properly, the problem is now only the image appear correctly.

public Image DeviationImage
            {
                get
                {
                    if (ShowDifference)
                    {
                        switch ((double)ValueIncreased)
                        {
                            case 1:
                                return (Image)Application.Current.Resources["ArrowUp"];

                            case 2:
                                return (Image)Application.Current.Resources["ArrowDown"];
                            case 0:
                                return (Image)Application.Current.Resources["ArrowEqual"];
                        }    
                    }
                    return null;
                }
            }

XAML - Where will I put the image

<Image Source="{Binding DeviationImage}" Height="20" Width="20"/>

XAML - Resources no xaml

        <Image x:Key="ArrowUp" Source="{telerik:RadGlyph Glyph='&#xe017;', Foreground='Blue'}"/>
        <Image x:Key="ArrowDown" Source="{telerik:RadGlyph Glyph='&#xe019;', Foreground='Blue'}"/>
        <Image x:Key="ArrowEqual" Source="{telerik:RadGlyph Glyph='&#xe121;', Foreground='Blue'}"/>

</UserControl.Resources>

1 answer

0


Here’s an example of how to change an image at runtime:

public class Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (!field.Equals(value))
        {
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
        return false;
    }
}
public class ImageModel : Model
{
    private Timer timer = new Timer();
    private static Random r = new Random();
    public ImageModel() {
        timer.Interval = TimeSpan.FromSeconds(2).TotalMilliseconds;
        timer.Elapsed += Timer_Elapsed;
        timer.Enabled = true;
        timer.Start();
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Dispatcher.CurrentDispatcher.Invoke(() => {
            var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            string btn = r.NextDouble() > 0.5 ? "up.png" : "down.jpg";
            Uri oUri = new Uri("pack://application:,,,/" + assemblyName + ";component/" + btn, UriKind.RelativeOrAbsolute);
            ImageBtn = new BitmapImage(oUri);
            ImageBtn.Freeze();
            OnPropertyChanged("ImageBtn");
        });
    }

    public BitmapImage ImageBtn {
        get; set;
    }
}

And the XML

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:ImageModel></local:ImageModel>
    </Window.DataContext>
    <StackPanel>
        <Image Source="{Binding ImageBtn}" Height="200"  Width="200"/>
    </StackPanel>
</Window>
  • I really appreciate the help! Could you tell me, how to return my image? it is a Static Resource Icons.Buttons.Down and Icons.Buttons.Up

  • I updated the question with the new code

  • @Olivf I updated the answer. It should be clearer now. Also because my previous answer was a bit far from the right answer.

  • Thank you Bruno, your reply helped me a lot. I managed, I changed some points using a convert.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.