tags:

views:

134

answers:

1

Hi, 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 = ????????

A: 

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);
    }
TheMachineCharmer
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
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
In visual studio right click on image and select `Properties`. In `Properties` set `Copy to Output Directory` to `Copy Always`.
TheMachineCharmer