有没有办法在WPF中操作按钮的背景图像?

时间:2012-01-09 00:03:37

标签: c# wpf

我需要给出背景图片的大小,因为我作为背景图片添加到我的按钮的图标图像(32x32)对按钮来说很大,看起来很糟糕,XAML代码是这样的:< / p>

<Window x:Class="apple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"> 
        <Grid>
        <Image Source="C:\Users\Fernando\Desktop\Eye-Mouse\apple\apple\img0.jpg" Stretch="Fill"/>
            <UniformGrid Name="gridx" Rows="6">
            </UniformGrid>
    </Grid>
</Window>

对于uniformGrid,我正在添加按钮,如下所示:

ImageBrush ib = new ImageBrush();
System.Windows.Controls.Button newBtn = new Button();
FileToImageIconConverter some = new FileToImageIconConverter(link[n]);
ImageSource imgSource = some.Icon;
ib.ImageSource = imgSource;
newBtn.Background = ib;
gridx.Children.Add(newBtn);

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

你可能想要使用Xaml&amp;数据绑定以填充均匀网格。这样,您可以根据需要设置Expression Blend中的按钮样式。

<Window x:Class="apple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"> 
        <Grid>
        <Image Source="C:\Users\Fernando\Desktop\Eye-Mouse\apple\apple\img0.jpg" Stretch="Fill"/>
        <!-- YourLinkList is the list that provides the link[n] in your example -->
        <ItemsControl ItemsSource="{Binding Path=YourLinkList}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="6"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button>
                        <Button.Background>
                            <ImageBrush>
                                <ImageBrush.ImageSource>
                                    <!-- {Binding .} means that the UriSource is bound to the item in the link list -->
                                    <BitmapImage UriSource="{Binding .}" DecodePixelWidth="32" DecodePixelHeight="32"/>
                                </ImageBrush.ImageSource>
                            </ImageBrush>
                        </Button.Background>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
    </ItemsControl> 
    </Grid>
</Window>

您还可以尝试将图像设置为按钮的内容,而不是将其用作背景。也许那会更好看。