Why WPF's Image control has different Data format in XAML and C# code?

兰树豪 381 Reputation points
2023-02-10T02:40:00.6+00:00

User's image

Above is the code inside xaml,the Image1‘s Source can be a address(string),but inside the c# code, see The following picture,The Image’s Source can't be a string。

Is there a more convenient way doing this in C# code? thanks!!

User's image

Developer technologies Windows Presentation Foundation
Developer technologies C#
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2023-02-10T05:46:05.36+00:00

    This is the syntax of xaml. You could refer to the XAML overview in WPF and the Code-Behind and XAML in WPF.

    The Image.Source Property is of the ImageSource type and uses the following method in Codebehind.

    image1.Source= new BitmapImage(new Uri("li.png", UriKind.Relative));
    
    
    

    Sample:

    <StackPanel>
            <Image x:Name="image" Source="li.png " Width="200" Height="200"/>
            <Image x:Name="image1" Width="200" Height="200"/>
        </StackPanel>
    
    
    Codebehind:
    
    
      public MainWindow()
            {
                InitializeComponent();
                image1.Source= new BitmapImage(new Uri("li.png", UriKind.Relative));
                
            }
    
    

    The result:

    User's image


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.