简体   繁体   English

将Button XAML更改为C#

[英]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: 在谷歌搜索中,我发现了以下XAML代码:

<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. 现在,我将这段代码转换为等效的C#代码,并尝试使用某些属性。 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. 我需要有关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 . 使用Cursors类获得Hand

DockPanel.Dock is an attached property, it's not a property of the button control. DockPanel.Dock是附加属性,它不是按钮控件的属性。 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: 然后设置绑定,创建适当的绑定对象,并将其传递给元素的SetBinding方法:

button.SetBinding(Button.CommandProperty, new Binding("DataContext.CloseCommand")
{
    RelativeSource = new RelativeSource { AncestorType = typeof(TabControl) },
});
button.SetBinding(Button.CommandParameterProperty, new Binding("Header"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM