1

当前在代码隐藏中,我动态创建 WPF Image 控件并将源绑定到自定义数据绑定。这最终将被添加到网格中以提供背景图像:

Image myImage = new Image();
myImage.Stretch = Stretch.UniformToFill;
myImage.SetBinding(Image.SourceProperty, myBinding);

问题是我想平铺这个图像,所以我能找到的唯一方法是创建一个 ImageBrush 并设置 TileMode 属性。但是没有“SetBinding”功能,那我该如何完成我需要的呢?

ImageBrush myBrush = new ImageBrush();
myBrush.TileMode = TileMode.Tile;
// Can't do this!
myBrush.SetBinding(ImageBrush.SourceImageProperty, myBinding);

有没有其他方法可以在代码隐藏中平铺这样的图像?

4

3 回答 3

4

您无需更改任何内容,只需使用 BindingOperations:

BindingOperations.SetBinding(myBrush, ImageBrush.ImageSourceProperty, myBinding);

您需要定义视口并用画笔填充视口:

MyBrush.Viewport = new Rect(0, 0, 0.1, 0.1);
// Create a rectangle and paint it with the ImageBrush.
Rectangle rec = new Rectangle();
rec.Stroke = Brushes.LimeGreen;
rec.StrokeThickness = 1;
rec.Fill = MyBrush;
于 2012-05-25T09:13:11.767 回答
1

我试过以下。在调试模式下,VisualBrush 的属性设置正确。当然,图像显示为拉伸图像。不知道为什么。希望能帮助到你。

财产

        public TileMode Mode { get; set; }

绑定

        VisualBrush myBrush = new VisualBrush();

        Uri uri = new Uri("picture.png", UriKind.RelativeOrAbsolute);
        ImageSource src = new BitmapImage(uri);
        myBrush.Visual = new Image() { Source = src };

        this.Mode = TileMode.Tile;

        Binding bind = new Binding() { Source = Mode };
        BindingOperations.SetBinding(myBrush, VisualBrush.TileModeProperty, bind);

        this.Background = myBrush;
于 2012-05-25T06:55:18.880 回答
0

我不喜欢代码隐藏,所以我很难快速编写代码隐藏示例。
这是标记示例:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Background>
        <ImageBrush ImageSource="Sample.jpg" TileMode="Tile" Viewport="0,0,0.5,0.5"/>
    </Grid.Background>
</Grid>

ImageSource="Sample.jpg"您可以编写任何绑定表达式,而不是硬编码图像 ( ): ImageSource="{Binding MyBackgroundImageUri}".

于 2012-05-25T06:52:02.940 回答