How to add a StackPanel in a Button using c# code behind (i.e. convert the following XAML to C# )? There is no Button.Children.Add...
<Button>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="foo.png"/>
</StackPanel>
</Button>
Image img = new Image();
img.Source = new BitmapImage(new Uri("foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
Set Button.Content instead of using Button.Children.Add
As a longer explanation:
Button is a control which "only has 1 child" - its Content.
Only very few controls (generally "Panels") can contain a list of zero or more Children - e.g. StackPanel, Grid, WrapPanel, Canvas, etc.
As your code already shows, you can set the Content of a Button to be a Panel - this would ehn allow you to then add multiple child controls. However, really in your example, then there is no need to have the StackPanel as well as the Image. It seems like your StackPanel is only adding Padding - and you could add the Padding to the Image rather than to the StackPanel if you wanted to.
Use like this
<Window.Resources>
<ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
<ImageBrush x:Key="LeftMenuBackgroundImageBrush"
ImageSource="{DynamicResource LeftMenuBackgroundImage}"/>
</Window.Resources>
and in Codebehind
Button btn = new Button();
btn.HorizontalContentAlignment = HorizontalAlignment.Stretch;
btn.VerticalContentAlignment = VerticalAlignment.Stretch;
StackPanel stk = new StackPanel();
stk.Orientation = Orientation.Horizontal;
stk.Margin = new Thickness(10, 10, 10, 10);
stk.SetResourceReference(StackPanel.BackgroundProperty, "LeftMenuBackgroundImageBrush");
btn.Content = stk;
In Xaml :
<Button x:Name="Btn" Click="Btn_Click" Orientation="Horizontal" Margin="10">
<StackPanel>
<Image Source="foo.png" Height="16" Width="16"/>
</StackPanel>
</Button>
In C# :
Button btn = new Button();
StackPanel panel = new StackPanel();
Image img = new Image
{
Source = "../foo.png"
}
panel.Children.Add(img);
btn.Content = panel;
I advise you to put the image in xaml resources :
<Window.Resources>
<BitmapImage x:Key="Img" UriSource="/Img/foo.png"/>
</Window.Resources>
And call it like this :
Image img = new Image
{
Source = (BitmapImage)FindResource("Img")
};
Related
I created a UWP solution and created a button. There are no problems with the buttons.
I do not know how to center the button in the window.
Code
StackPanel stackPanel1 = new StackPanel();
Button TestButton = new Button();
TestButton.Content = "Test";
stackPanel1.Children.Add(subscribeButton);
Window.Current.Content = stackPanel1;
This line is all you need.
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
Changing the position of the button to half of the form's width and height will work.
Point point = new Point(this.Width / 2 - (button1.Width/2), this.Height / 2 - (button1.Height/ 2));
button1.Location = point;
The added - (button1.Width/2) is because the button's position is based on the upper right hand corner of the button, and not actually the center.
You can set HorizontalAlignment something like these inside the stackpanel...
<StackPanel Margin="10,0,0,0" Orientation="Horizontal" Grid.Column="0">
<TextBlock Grid.Column="1" Grid.Row="0" FontSize="16" HorizontalAlignment="Center">2. Draw a pattern</TextBlock>
<Button x:Name="DeleteSiteButton" Content="Delete Site"
HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Top" Click="DeleteSiteButton_Click"/>
<Button x:Name="AddSiteButton" Content="Add Site" HorizontalAlignment="Right"
Margin="10,0,0,0" VerticalAlignment="Top" Click="AddSiteButton_Click"/>
</StackPanel>
StackPanel control arranges child elements into a single line that can be oriented horizontally or vertically. When the Orientation property is set to Vertical(The default value is Vertical), the VerticalAlignment property of the button control will be invalid. Similarly, when the Orientation property is set to Horizontal, the HorizontalAlignment property of the button control will be invalid.
If you add a button control into a StackPanel, the HorizontalAlignment property and VerticalAlignment property of the button control will not work at the same time, that is, the button control can not be centered in a StackPanel.
We suggest that you could add the button control to a Grid panel, like this:
Grid gridPanel1 = new Grid();
Button TestButton = new Button();
TestButton.Content = "Test";
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
TestButton.VerticalAlignment = VerticalAlignment.Center;
gridPanel1.Children.Add(TestButton);
Window.Current.Content = gridPanel1;
I'm adding a stackpanel to a mapcontrol. like below
But some of the points added before are on the top of my stackpanel. How to set my stackpanel topmost?
XAML:
<Grid x:Name="gridMain">
<maps:MapControl
x:Name="mapControl"
ZoomInteractionMode="GestureAndControl"
TiltInteractionMode="GestureAndControl"
RotateInteractionMode="GestureAndControl">
<!--ZoomLevel="{x:Bind ViewModel.ZoomLevel, Mode=OneWay}"
Center="{x:Bind ViewModel.Center, Mode=OneWay}"-->
<maps:MapItemsControl x:Name="MapItems">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<Grid Tapped="MagPoint_Tapped" maps:MapControl.NormalizedAnchorPoint="{Binding NormalizedAnchorPoint}" maps:MapControl.Location="{Binding Location}">
<Ellipse Canvas.ZIndex="0" Width="{Binding Mag5}" Height="{Binding Mag5}" Fill="{Binding MagColor}"/>
<!--<TextBlock Text="{Binding Mag}"/>-->
</Grid>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:MapControl>
</Grid>
And add panel code.
StackPanel sp = new StackPanel();
sp.Background = new SolidColorBrush(Colors.White);
sp.CornerRadius = new CornerRadius(15);
sp.BorderBrush = new SolidColorBrush(Colors.LightGray);
sp.BorderThickness = new Thickness(1);
sp.Width = 260;
sp.MinHeight = 180;
sp.Padding = new Thickness(10);
Canvas.SetZIndex(sp, 99999);
mapControl.Children.Add(sp);
Windows.UI.Xaml.Controls.Maps.MapControl.SetLocation(sp, new Geopoint(new BasicGeoposition { Longitude = (double)fi.geometry.coordinates[0], Latitude = (double)fi.geometry.coordinates[1] }));
Windows.UI.Xaml.Controls.Maps.MapControl.SetNormalizedAnchorPoint(sp, new Point(0.5, 1));
Your way of setting the ZIndex wouldn't work because the StackPanel and the items inside MapItemsControl are in different hosts.
With the help of Live Visual Tree, you can find out how exactly they get laid out.
In the screenshot above, the StackPanel's host (i.e. the first Canvas) is placed behind the MapOverlayPresenters host (i.e. the second Canvas where MapItemsControl is inserted). So in order to have the StackPanel sit above them, you will need to manually set the ZIndex of the first Canvas to 1.
Once you understand this, the solution becomes simple -
Loaded += (s, e) =>
{
// GetChildByName comes from
// https://github.com/JustinXinLiu/Continuity/blob/0cc3d7556c747a060d40bae089b80eb845da84fa/Continuity/Extensions/UtilExtensions.cs#L44
var layerGrid = mapControl.GetChildByName<Grid>("LayerGrid");
var canvas1 = layerGrid.Children.First();
Canvas.SetZIndex(canvas1, 1);
};
Hope this helps!
I'm completely new to WPF and I need some help putting an image in my progress bar (programmatically).
I found this (and it works):
<ProgressBar.Template>
<ControlTemplate>
<Grid>
<Image Name="PART_Track" Source="MyImage" Stretch="Fill"/>
<Rectangle Name="PART_Indicator" Fill="BlanchedAlmond" HorizontalAlignment="Left"/>
</Grid>
</ControlTemplate>
</ProgressBar.Template>
I just need some help converting that XAML code to C# code.
This will get you started :
FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));
FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.Name = "PART_Track";
ImageSource source = new BitmapImage(...); // create it
image.SetValue(Image.SourceProperty, source);
image.SetValue(Image.StretchProperty, Stretch.Fill);
grid.AppendChild(image);
FrameworkElementFactory rectangle = new FrameworkElementFactory(typeof(Rectangle));
rectangle.Name = "PART_Indicator";
rectangle.SetValue(Rectangle.FillProperty, new SolidColorBrush(Colors.BlanchedAlmond));
rectangle.SetValue(Rectangle.HorizontalAlignmentProperty, HorizontalAlignment.Left);
grid.AppendChild(rectangle);
ControlTemplate ct = new ControlTemplate(typeof(ProgressBar));
ct.VisualTree = grid;
MyProgressBar1.Template = ct;
How to: Fill a ListView by using C# instead of using XAML
I would like to fill a ListView by using C# (WPF), not by using XAML. The reason for this is, that we do not know the number of elements before runtime.
This is my working XAML code:
<ListView Name="listView_BusinessContacts" SelectionMode="Single">
<ListViewItem Selected="ListViewItem_Selected">
<DockPanel DockPanel.Dock="Top" Name="dockPanel_1">
<Image DockPanel.Dock="Left" Source="/X;component/Images/folder.png" Stretch="None" />
<Label Content="Test 123" DockPanel.Dock="Right" Name="label_1" />
</DockPanel>
</ListViewItem>
</ListView>
My idea is first to create the ListViewItem. After that, I could create the DockPanel. But now, I do not know, how to add two elements to a DockPanel (here: Image and Label). After that, I would add the DockPanel to the ListViewItem and than I would add that ListViewItem to the ListView.
I hope, that you understand what I want to do.
Solution by SynerCoder:
public void SetListViewItems()
{
foreach (var item in File.ReadAllLines(#"C:\Companies\Companies.txt", Encoding.UTF8))
{
Image image = new Image();
image.Source = new BitmapImage(new Uri(#"Images\folder.png", UriKind.Relative));
image.Stretch = Stretch.None;
Label label = new Label();
label.Content = "Test 123";
DockPanel.SetDock(image, Dock.Left);
DockPanel.SetDock(label, Dock.Right);
DockPanel dockPanel = new DockPanel();
dockPanel.Children.Add(image);
dockPanel.Children.Add(label);
ListViewItem listViewItem = new ListViewItem();
listViewItem.Content = dockPanel;
listView_BusinessContacts.Items.Add(listViewItem);
}
}
You can use the following code to create your listview, use the static SetDock method of the DockPanel to set the docking positions.
var listView = new ListView();
foreach (var item in something)
{
var image = new Image();
image.Source = ...;
image.Stretch = Stretch.None;
var label = new Label();
label.Content = "Test 123";
DockPanel.SetDock(image, Dock.Left);
DockPanel.SetDock(label, Dock.Right);
var dockPanel = new DockPanel();
dockPanel.Children.Add(image);
dockPanel.Children.Add(label);
var item = new ListViewItem();
item.Content = dockPanel;
listView.Items.Add(item);
}
In WPF:
<Button Width="24" Height="24" >
<Image Source="pack://application:,,,/res/x.png" VerticalAlignment="Center"/>
</Button>
How can I mimic this in C#? I can't find any method in the Button class that adds children.
Button is a Content control so you just have to use the Buttons Content property
Example:
Button myButton = new Button
{
Width = 24,
Height = 24,
Content = new Image
{
Source = new BitmapImage(new Uri("image source")),
VerticalAlignment = VerticalAlignment.Center
}
};