Change Button XAML to C# - c#

I have a tab control in which I am adding tab items programmatically. I want to have a close button with each tab item. On googling I found below XAML code for it:
<Button Content="X" Cursor="Hand" DockPanel.Dock="Right"
Focusable="False" FontFamily="Courier" FontSize="9"
FontWeight="Bold" Margin="5,0,0,0" Width="16" Height="16" />
Now, I am converting this code into equivalent C# code and struggling with some of the properties. Below given is the code which I have till now.
var CloseButton = new Button()
{
Content = "X",
Focusable = false,
FontFamily = FontFamily = new System.Windows.Media.FontFamily("Courier"),
FontSize = 9,
Margin = new Thickness(5, 0, 0, 0),
Width = 16,
Height = 16
};
I want help with properties like Cursor, DockPanel.Dock. Any help on this is much appreciated. Thanks !

Cursors are a fairly standard set of types. There are static classes out there that give you access to many of them. Use the Cursors class to get the Hand.
DockPanel.Dock is an attached property, it's not a property of the button control. You have to use the property setters for that dependency object or other convenience methods if available.
var button = new Button
{
Content = "X",
Cursor = Cursors.Hand,
Focusable = false,
FontFamily = new FontFamily("Courier"),
FontSize = 9,
Margin = new Thickness(5, 0, 0, 0),
Width = 16,
Height = 16
};
// this is how the framework typically sets values on objects
button.SetValue(DockPanel.DockProperty, Dock.Right);
// or using the convenience method provided by the owning `DockPanel`
DockPanel.SetDock(button, Dock.Right);
Then to set the bindings, create the appropriate binding object and pass it to the element's SetBinding method:
button.SetBinding(Button.CommandProperty, new Binding("DataContext.CloseCommand")
{
RelativeSource = new RelativeSource { AncestorType = typeof(TabControl) },
});
button.SetBinding(Button.CommandParameterProperty, new Binding("Header"));

Related

Change font family programmatically in wpf

I'm creating a WPF application.
I have created a folder in my solution and I have some fonts in it.
How can I change programmatically the TextBlock FontFamily ?
XAML
<TextBlock
Name="textBlock"
Background="AntiqueWhite"
Foreground="Navy"
FontFamily="Century Gothic"
FontSize="12"
FontStretch="UltraExpanded"
FontStyle="Italic"
FontWeight="UltraBold"
LineHeight="Auto"
Padding="5,10,5,10"
TextAlignment="Center"
TextWrapping="Wrap"
Typography.NumeralStyle="OldStyle"
Typography.SlashedZero="True"
>
<Run Background="LightGreen">Text run 1.</Run>
<LineBreak/><Run Background="LightBlue">Text run 2.</Run>
<LineBreak/><Run Background="LightYellow">Text run 3.</Run>
</TextBlock>
Code behind
TextBlock textBlock = new TextBlock(new Run("A bit of text content..."));
textBlock.Background = Brushes.AntiqueWhite;
textBlock.Foreground = Brushes.Navy;
textBlock.FontFamily = new FontFamily("Century Gothic");
textBlock.FontSize = 12;
textBlock.FontStretch = FontStretches.UltraExpanded;
textBlock.FontStyle = FontStyles.Italic;
textBlock.FontWeight = FontWeights.UltraBold;
textBlock.LineHeight = Double.NaN;
textBlock.Padding = new Thickness(5, 10, 5, 10);
textBlock.TextAlignment = TextAlignment.Center;
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Typography.NumeralStyle = FontNumeralStyle.OldStyle;
textBlock.Typography.SlashedZero = true;
if you want to load a custom font
controlID.FontFamily = new FontFamily("file:///Font
Full Path");
Take the Control e.g. a TextBlock and set its style with
Style style = new Style(typeof(TextBlock));
Then add a setter using a resource as follows
style.Setters.Add(new Setter(TextBlock.FontFamilyProperty, this.FindResource("NameOfResource")));
Finally set the style to the control...
myTextBlock.Style = style;

How do I use an array from code in the xaml file? C#

I am working with animations using Blend.
I created a storyboard, which changes the margin of a button to be on the exact same position as one of my 55 textboxes that are placed on a grid.
The animation should move the button to one of the 55 textboxes depending in on which textbox I click
I created an array which consists of all the margins from the 55 textboxes and I now want to use this array in xaml.
I tried to use Resources.Add and StaticResource but it is not working.
Using arrays in XAML is quite simple: first you declare your margins array as a public property of your Window:
public Thickness[] MyArray { get; set; }
Then you initialize it in your Window constructor:
MyArray = new Thickness[50];
MyArray[0] = new Thickness(5, 5, 5, 5);
MyArray[1] = new Thickness(10, 10, 10, 10);
// ...
DataContext = this;
And then you bind your buttons' Margin properties to each element of your array:
<TextBox x:Name="TextBox1" Margin="{Binding MyArray[0]}" />
<TextBox x:Name="TextBox2" Margin="{Binding MyArray[1]}" />
Anyway it's a much better idea to use ObservableCollection instead of Array because otherwise your view won't be notified about the changes done inside your array from code behind:
public ObservableCollection<Thickness> MyCollection { get; set; }
public MainWindow()
{
InitializeComponent();
MyCollection = new ObservableCollection<Thickness>();
MyCollection.Add(new Thickness(5, 5, 5, 5));
MyCollection.Add(new Thickness(10, 10, 10, 10));
// ...
DataContext = this;
}
And in your XAML the bindings remain the same:
<TextBox x:Name="TextBox1" Margin="{Binding MyCollection[0]}" />
<TextBox x:Name="TextBox2" Margin="{Binding MyCollection[1]}" />

How to add a button with Tooltip, Transparent background and Glyph from code?

In XAML, you can add a button like this:
<Button Height="Auto" Width="Auto" Background="Transparent" ToolTipServie.ToolTip="Tooltip here" ToolTipService.Placement="Bottom" />
However I cannot achieve similar approach with C#. Assume I have a Stackpanel named "toolbar":
toolbar.Children.Add(new Button {
Name = "undo",
FontFamily = new FontFamily("Segoe MDL2 Assets"),
Content = "&#xE10E",
Opacity = 100,
});
When I debug the code, it adds a button with squares, gray background. Also I don't know how to add a tooltip to the button.
I tried searching for help, nothing helped. :(
Any help is much appreciated. Thanks.
The tooltip isn't a normal DP, it's an attached property via the ToolTipService class, so you need to add it as such:
var button = new Button
{
Name = "undo",
FontFamily = new FontFamily("Segoe MDL2 Assets"),
Content = "&#xE10E",
Opacity = 100,
};
ToolTipService.SetToolTip(button, "Tooltip here");
ToolTipService.SetPlacement(button, PlacementMode.Bottom);
toolbar.Children.Add(button);

ExpanderView assigning DataTemplate

I've got a StackPanel which I need to fill in with ExpanderViews based on my data.
I am creating the ExpanderViews in code-behind and assigning to it, the DataTemplate present in the XAML.
The problem is, I am able to create the ExpanderView programmatically, but the DataTemplate approach doesn't work. All I can see is the "Expander Header" which doesn't show the items after click.
However, I can add Items manually to the ExpanderView and it shows the Items.
Please help!
C# Code:
ExpanderView expandOne = new ExpanderView()
{
Width = 400,
Margin = new Thickness(2),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Expander = new Border()
{
Width = 400,
Background = new SolidColorBrush(Colors.Brown),
Child = new TextBlock()
{
Text = "Expander Header",
FontSize = 34,
Foreground = new SolidColorBrush(Colors.Black),
Margin = new Thickness(40, 5, 5, 5),
},
},
};
// Assign DataTemplate
DataTemplate temp = (DataTemplate)FindName("ItemTemplateName");
expandOne.ItemTemplate = temp;
// add ExpanderView to StackPanel
this.MyStackPanel.Children.Add(expandOne);
XAML Code:
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="ItemTemplateKey" x:Name="ItemTemplateName">
<ListBox Grid.Row="0" x:Name="ItemListBox">
<ListBox.Items>
<TextBlock Text="Filter Content 1" Foreground="Black"/>
<TextBlock Text="Filter Content 2" Foreground="Black"/>
<TextBlock Text="Filter Content 3" Foreground="Black"/>
</ListBox.Items>
</ListBox>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
If anyone still looking for an answer, I solved this by using the solution mentioned in
DataBinding to WP8 Toolkit ExpanderView

Adding an Image inside a Button programmatically

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
}
};

Categories