Search code examples
c#windows-phone-8viewbox

How to Set ViewBox Image Source in Code Behind


In following a code sample here http://msdn.microsoft.com/en-us/library/ms752301(v=vs.110).aspx I'd like to be able to change the following XAML code to C# and set the ViewBox source in code behind. What is the proper method of doing this? Must I set the Child of the ViewBox?

<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
    <Viewbox MaxWidth="500" MaxHeight="500" Name="vb1">
        <Image Source="tulip_farm.jpg"/>
    </Viewbox>    
</StackPanel>

Solution

  • The easiest way to achieve this is give a name to that specific image so you can set the source anywhere you want in code:

             <Image x:Name="MyImage" Source="tulip_farm.jpg"/>
    

    And in c#:

            BitmapImage bitimg = new BitmapImage(new Uri(@"/MyNewLink.jpg", UriKind.Relative));
            MyImage.Source = bitimg as ImageSource;