C# 使用WPF c将System.Windows.Controls.Button图像作为内容#

C# 使用WPF c将System.Windows.Controls.Button图像作为内容#,c#,wpf,C#,Wpf,这是代码,图像未显示。如果我使用文本内容,它会显示,但图像不会显示。我错过了什么 //Begin btnLine Code. btnLine = new System.Windows.Controls.Button(); // Create the image element. Image simpleImage = new Image(); simpleImage.

这是代码,图像未显示。如果我使用文本内容,它会显示,但图像不会显示。我错过了什么

            //Begin btnLine Code.
             btnLine = new System.Windows.Controls.Button();
            // Create the image element.
            Image simpleImage = new Image();    
            simpleImage.Width = 200;
            simpleImage.Margin = new Thickness(5);

            // Create source.
            BitmapImage bi = new BitmapImage();
            // BitmapImage.UriSource must be in a BeginInit/EndInit block.
            bi.BeginInit();

            bi.UriSource = new Uri(InstallDir+@"\ToolbarImages\line1.jpg",UriKind.RelativeOrAbsolute);
            bi.EndInit();
            // Set the image source.
            simpleImage.Source = bi;

            btnLine.Content= bi;//image button Does not work
            //btnLine.Content= simpleImage;//image button Does not work
            //btnLine.Content= "o-o";//text button Does work

            btnLine.Click += btnLine_Click;
            chartWindow.MainMenu.Add(btnLine);
改变

btnLine.Content= bi;


通常,在XAML中做这些事情要容易得多。将映像设置为本地资源相当简单。这是一个简单的版本

 <Grid>
    <Button>
        <Image Source="ToolbarImages\image1.jpg"/>
    </Button>
 </Grid>


如果您正在寻找一种动态方法来实现这一点,那么您应该在源映像上使用绑定,这样您就可以利用wpf的强大功能

另外,请确保“生成操作”设置为“内容”,并复制到输出目录以始终用于图像。
 <Grid>
    <Button>
        <Image Source="ToolbarImages\image1.jpg"/>
    </Button>
 </Grid>