简体   繁体   中英

Insert an Image to a Button in code behind

I have the following piece of XAML that add an image in a Button. The XAML works fine:

<Button>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Image Grid.Row="0" Grid.Column="0" Source="Images/reset.png"/>
    </Grid>
</Button>

I tried to convert the above XAML to C# but didn't get it to work

Button btn = new Button();

Grid imgGrid = new Grid();
imgGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
imgGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });

Image img = new Image();
img.Source = new BitmapImage(new Uri("/ReighGaugeSoftware1;component/Images/config.png"));
img.Stretch = Stretch.Uniform;
imgGrid.Children.Add(img);
Grid.SetRow(img, 0);
Grid.SetColumn(img, 0);

btn.Content = imgGrid;

It was a straight-forward conversion, but the debugging throws me a "XamlParseException was unhandled" which I cannot relate to my code. Can anyone point out where it went wrong?

There is an exception being thrown in your code but it's obscured by the XamlParseException. My guess is that the image path is wrong.

In Visual Studio, key Ctrl-Alt-E to bring up the Exceptions window, then ensure that Common Language Runtime Exceptions is checked in both columns, then run your code.

Execution will break at the line of code where the error is occurring, it should be easy enough to fix from there (if not, post the Exception text).

在此处输入图片说明

唯一的不同是Uri,所以我怀疑它可能有问题,请参阅pack URI上的页面

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM