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);
    }
3
  • 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
    – Anu
    Commented Feb 11, 2010 at 5:21
  • 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."
    – Anu
    Commented Feb 11, 2010 at 5:24
  • In visual studio right click on image and select Properties. In Properties set Copy to Output Directory to Copy Always. Commented Feb 11, 2010 at 6:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.