将按钮XAML更改为C#

Nar*_*ani 2 c# wpf xaml tabitem

我有一个选项卡控件,我在其中以编程方式添加选项卡项.我希望每个标签项都有一个关闭按钮.在谷歌搜索我发现下面的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" />    
Run Code Online (Sandbox Code Playgroud)

现在,我正在将此代码转换为等效的C#代码并与一些属性进行斗争.下面给出的是我到现在为止的代码.

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
};    
Run Code Online (Sandbox Code Playgroud)

我想要帮助像Cursor,DockPanel.Dock这样的属性.对此有任何帮助非常感谢.谢谢 !

Jef*_*ado 6

游标是一组相当标准的类型.有一些静态类可以让你访问其中许多类.使用Cursors该类来获取Hand.

DockPanel.Dock是附加属性,它不是按钮控件的属性.您必须使用该依赖项对象的属性设置器或其他方便方法(如果可用).

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);
Run Code Online (Sandbox Code Playgroud)

然后设置绑定,创建适当的绑定对象并将其传递给元素的SetBinding方法:

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

  • 谢谢@Clemens整理它.自从我上次不得不以编程方式在WPF中做任何事情已经有很长一段时间了.特别感谢,因为我正准备去睡觉.:) (2认同)