开发者

Insert an Image to a Button in code behind

开发者 https://www.devze.com 2023-02-22 14:26 出处:网络
I have the following piece of XAML that add an image in a Button. The XAML works fine: <Button> <Grid>

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 wor开发者_运维问答k

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).

Insert an Image to a Button in code behind


The only think that is different is the Uri, so i suspect there might be something wrong with it, see this page on pack URIs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号