在 WPF 中,可以使用依赖属性来定义按钮集合。下面是一个示例代码,演示了如何创建一个按钮集合,并将其作为依赖属性使用:
using System.Windows;
using System.Windows.Controls;
public class ButtonCollection : DependencyObject
{
public static readonly DependencyProperty ButtonsProperty = DependencyProperty.Register(
"Buttons", typeof(Button[]), typeof(ButtonCollection));
public Button[] Buttons
{
get { return (Button[])GetValue(ButtonsProperty); }
set { SetValue(ButtonsProperty, value); }
}
}
public class MainViewModel
{
public ButtonCollection ButtonCollection { get; } = new ButtonCollection();
public MainViewModel()
{
Button[] buttons = new Button[]
{
new Button() { Content = "Button 1" },
new Button() { Content = "Button 2" },
new Button() { Content = "Button 3" }
};
ButtonCollection.Buttons = buttons;
}
}
在 XAML 中使用这个依赖属性的示例:
这个示例中,ButtonCollection
是一个自定义的 DependencyObject
,它包含一个 Buttons
的依赖属性。MainViewModel
是一个实现了 INotifyPropertyChanged
接口的类,它包含一个 ButtonCollection
的实例。在构造函数中,我们创建了一个包含三个按钮的数组,并将它赋值给 ButtonCollection.Buttons
属性。在 XAML 中,我们使用 ItemsControl
来绑定 ButtonCollection.Buttons
,并使用 WrapPanel
来自动换行显示按钮。
上一篇:按钮揭示图像的问题
下一篇:按钮激活的UART消息