5

Im doing apllication WPF with C#. I have three kinds of images in my folder "Data". I have Iamge abd textblock and one button. when i press button,it will display text in textblock and depends on the text,image may vary.How can i do add image at runtime.

 public void Adddata(string lData)
        {          
            Text1.Text = lData; 
            Img1.Source = "data\vista_flag.png";
        }

I know i coded wrongly.but I dont know what can i do for that. Img1.Source = ????????

1 Answer 1

3

XAML:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Canvas Name="myCanvas">
    <StackPanel Name="stkPanel">
        <Button Name="btnLoadImage" Click="btnLoadImage_Click" >Load Image</Button>
    </StackPanel>
</Canvas>

C# Button Click Code:

 private void btnLoadImage_Click(object sender, RoutedEventArgs e)
    {
        string src = @"C:\Documents and Settings\pdeoghare\My Documents\My Pictures\YourImage.jpg";

        Image img = new Image();

        img.Source = new ImageSourceConverter().ConvertFromString(src) as ImageSource;

        stkPanel.Children.Add(img);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Im getting error.. string src = @"data\vista_flag.png"; Img1.Source = new ImageSourceConverter().ConvertFromString(src) as ImageSource; Stack1.Children.Add(Img1); Im getting error in img1.source = new ImageSource...... Line
Sorry,when i place my image in debug folder i didnot get that error. But now error occurs in last line.It tells "Specified Visual is already a child of another Visual or the root of a CompositionTarget."
In visual studio right click on image and select Properties. In Properties set Copy to Output Directory to Copy Always.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.