2017-05-06 85 views
2

我有一个选项卡控件,我在其中以编程方式添加选项卡项目。我想要每个标签项都有一个关闭按钮。在谷歌上搜索,我发现下面的XAML代码吧:更改按钮XAML到C#

<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" />  

现在,我将这个代码转换成等价的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 
};  

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

+2

看一看这一https://msdn.microsoft.com/en-us /library/system.windows.controls.button(v=vs.110).aspx你需要的唯一属性,我没有找到是DockPanel.Dock。我认为你使用的是System.Windows.Forms.Button而不是System.Windows.Controls.Button –

+2

DockPanel.Dock可以通过一个DockPanel对象来处理。请参阅[this](https://msdn.microsoft.com/en-us/library/system.windows.controls.dockpanel.dock(v = vs.110).aspx)中的用法以供参考 – YashTD

+0

并且由于YashTD编写了Dock Panel可以用这种方式处理DockPanel.SetDock(CONTROL_NAME,Dock.Right); –

回答

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

然后设置绑定,创建相应的绑定对象,并把它传递给元素的SetBinding方法:

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

在button.SetValue上发生错误:WindowsBase.dll中发生未处理的异常'System.ArgumentException' 附加信息:'System.Windows.Data.Binding'不是有效值为财产'命令'。 –

+1

@NareshRavlani它应该是SetBinding而不是SetValue。 – Clemens

+0

对不起。我有VM和CloseCommand。我想我需要一些咖啡:P –