【发布时间】:2015-01-17 05:06:21
【问题描述】:
删除了我的旧问题,以便我提出更具体的问题。我使用来自http://www.c-sharpcorner.com/uploadfile/mahesh/image-viewer-in-wpf/ 的代码作为基础。允许用户浏览要打开和显示的图像文件。我想显示一张图片,然后让用户在上面做标记。我决定为此使用画布。现在,我不知道如何让用户选择的图像作为背景。我收到一条错误消息,提示“System.Windows.Shapes.Path 不包含‘Background’的定义,并且找不到接受‘System.Windows.Shapes.Path’类型的第一个参数的扩展方法‘Background’ ...”来自“canvas1.Background = Brush;”的行。我已经查找了设置画布背景的方法,其中一些仅涉及使用 xaml 代码,但随后出现其他错误。
XAML:
<Window x:Class="CanvasStuff.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="409" Width="574">
<Grid >
<Label Content="Image" Height="32" HorizontalAlignment="Left" Margin="11,10,0,0"
Name="selectedFileName" VerticalAlignment="Top" Width="393"
Background="LightGray" BorderBrush="Gray" BorderThickness="1"/>
<Button Content="Browse File" Height="34" HorizontalAlignment="Left" Margin="410,8,0,0"
Name="BrowseButton" VerticalAlignment="Top" Width="119"
Foreground="Maroon" FontSize="16" FontFamily="Georgia" Click="BrowseButton_Click" />
<Canvas>
<Path Canvas.Left="61" Canvas.Top="28" Width="133" Height="98" Fill="Blue"
Stretch="Fill" Data="M61,125 L193,28" Name="canvas1"/>
</Canvas>
</Grid>
</Window>
代码背后:
namespace CanvasStuff
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));
canvas1.Background = brush; #error here
BitmapImage bitmap = new BitmapImage();
}
}
}
}
【问题讨论】:
-
改用
UriKind.Absolute,所选文件当然应该在某个绝对路径中。 -
我改变了它,但我得到了同样的错误。我认为我在 .xaml 中没有正确使用 Name=canvas1。当我搞砸 .background 错误消失但我得到一个 canvas1 is not used in current context 错误时。
-
您将
Name设置为内部Path,而不是Canvas,为什么这对您来说如此困难的命名问题? -
反正我之前的评论还是你的问题,不信?正确命名 Canvas 后,保留代码并运行它。
-
是的,我在查看下面的 bonyjoe 示例后才注意到这一点。从前面的例子那里有那条路,忘了摆脱它。谢谢!
标签: c# wpf image wpf-controls