Search code examples
c#wpfxamltabitem

Change Button XAML to 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 !


Solution

  • 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"));