Muhammad Abbas Muhammad Abbas - 9 days ago 5
C# Question

How to resize Background Image of a Button in wpf

I am making an Application in Wpf. I recently encountered an issue. I want to resize the image that is shown as background image of a button created programmatically on run time.
More Presizely I want to decrease the height of Image.
What I have done so far is:

SqlDataAdapter adp = new SqlDataAdapter("Load_inventory_in_Pos", conn);
adp.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
adp.SelectCommand.Parameters.Add("@CategorID", System.Data.SqlDbType.VarChar, 50).Value = id;
adp.SelectCommand.Parameters.Add("@Operation", System.Data.SqlDbType.VarChar, 50).Value = "LoadItems";
System.Data.DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
ProductsWrapPanel.Children.Clear();
foreach (System.Data.DataRow rowvar in dt.Rows)
{
//Here Creating Button on Runtime.

Button button = new Button();
string quantity = rowvar["Current_Stock"].ToString();
if (quantity != "" && quantity != null)
{
button.Content = Environment.NewLine + "Quantity:[" + rowvar["Current_Stock"].ToString() + "]" + Environment.NewLine + "." + rowvar[2].ToString() + ".";
button.Height = 150;
button.Width = 150;
ProductsWrapPanel.Children.Add(button);
button.Margin = new Thickness(10, 10, 0, 0);
new SolidColorBrush(Color.FromArgb(0, 166, 161, 16));
button.BorderThickness = new Thickness(5);
button.VerticalContentAlignment = VerticalAlignment.Bottom;
button.Click += (sender, EventArgs) => { btnNew_Click(sender, EventArgs, rowvar["Product_Code"].ToString()); };

byte[] getImg = new byte[0];
getImg = (byte[])rowvar["Image"];
Image image = new Image();
using (MemoryStream stream = new MemoryStream(getImg))
{
image.Source = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
var brush = new ImageBrush();
brush.ImageSource = image.Source;
button.Background = brush;
data.Product_Name = rowvar[2].ToString();
data.Quantity = quantity.ToString();

}
}


What I Got is:
this Image

And What I need is this.

Required Image.

Thanks in Advance.

Answer

Actually, you don't have to resize the image programmatically here at all. You can define a Style and then assign it to your Button when you create it, and take care of the resizing in the ControlTemplate of the Style:

<Application.Resources>
        <Style x:Key="style_MyButton" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}" >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Button HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
                            <Grid >
                                <Grid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                            <Border Background="{TemplateBinding Background}" />
                            <TextBlock Grid.Row="1"
                                           Text="{TemplateBinding Content}"
                                           HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                           Margin="{TemplateBinding Padding}" 
                                           SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                           VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Grid>
                        </Button>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>

then, the codebehind:

        Button button = new Button();
        button.Content = "SomeTetx Some text";
        button.Height = 150;
        button.Width = 150;
        grid.Children.Add(button);
        button.Margin = new Thickness(10, 10, 0, 0);
        button.BorderThickness = new Thickness(5);

        // here is the important line:
        button.Style = (Style)Application.Current.FindResource("style_MyButton");

        Image image = new Image();
        var source=new BitmapImage( new Uri (imagepath));
        source.Freeze();
        image.Source = source;
        var brush = new ImageBrush();
        brush.ImageSource = image.Source;
        // this is how you can manipulate the stretch mode:
        brush.Stretch = Stretch.UniformToFill;
        button.Background = brush;

result:

enter image description here

Comments