WPF从图像资源分配边框背景



我正在尝试模拟网格库存系统。我有一些排成一排的网格。我有一个图像的资源。我遇到的错误是:

不能隐式将类型'System.Windows.Controls.image'转换为'System.Windows.Media.Media.brush'

如果我将图像施放到ImageBrush,则该项目会立即崩溃。

<Grid x:Name="MasterGrid" Margin="0">
    <Grid.Resources>
        <Image x:Key="notepad" Source="notepad_16x16.jpg" />
    </Grid.Resources>
// create a border and set it's background image
Border border = new Border();
border.Visibility = System.Windows.Visibility.Visible;
var img = (Image)MasterGrid.FindResource("notepad");
border.Background = img;
// add the border to the grid
Grid.SetRow(border, 0);
Grid.SetColumn(border, 1);
Grid.SetRowSpan(border, 1);
Grid.SetColumnSpan(border, 1);
InvGrid.Children.Add(border);

border.background期望刷子,您正在用图像填充它。您需要从图像资源

创建图像刷
border.Background = new ImageBrush((BitmapImage)FindResource("notepad"));

您的图像资源应定义如下:

<Grid.Resources>
    <BitmapImage x:Key="notepad" UriSource="images/notepad_16x16.jpg" />
</Grid.Resources>
    <Grid.Background>
        <ImageBrush ImageSource="C:... your path to the imagenotepad_16x16.jpg"/>
    </Grid.Background>

这对我有用而无需设置边界。

最新更新