我还是WPF的新手(只用它完成了一些小项目)。我正在尝试制作一组重复的控件(用户可以添加/删除这些组),数据绑定到自定义类。示例UI:
([UserButton1] [UserButton2]) <--each of these () is a separate group of buttons
([Cheese] [Wine] )
([Wallace] [Gromit] )
[Add] <--this button can add more groups
数据绑定到类似这样的类的列表(伪代码):
class UserButtons {
string UserButton1 = "UserButton1"
string UserButton2 = "UserButton2"
}
,例如
List<UserButtons> = {
[0]: UserButton1, UserButton2
[1]: Cheese, Wine
[2]: Wallace, Gromit
}
我知道这是WPF创建的那种东西,但我无法弄明白该如何去做。
我应该使用某种ListView吗? DataTemplate会有帮助吗? StackPanel听起来不错,但它没有列表的数据绑定......或者它?我甚至不确定如何为上面指出的按钮组进行数据绑定工作(如果这对你有意义...对不起的坏例子)。有没有人对这个问题有任何见解?
我搜索过试图找到一个与此有关的问题并没有看到一个,也许是因为我不确定要搜索什么。所以,对不起,如果这是一次无意的欺骗。
答案 0 :(得分:4)
我不完全确定你在寻找什么,但我希望下面的例子有所帮助。我使用了ItemsControl,其ItemsSource设置为UserButtons的集合。它的ItemTemplate属性设置为StackPanel,显示两个按钮,每个按钮的Content属性绑定到UserButtons中的属性。
XAML:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
</Window.Resources>
<StackPanel Orientation="Vertical">
<ItemsControl x:Name="itemsControl" Background="LightBlue">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="{Binding Button1}" Width="100"/>
<Button Content="{Binding Button2}" Width="100"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Width="50" Click="Button_Click">Add</Button>
</StackPanel>
</Window>
代码隐藏:
public partial class MainWindow : Window
{
ObservableCollection<UserButtons> oc;
public MainWindow()
{
InitializeComponent();
oc = new ObservableCollection<UserButtons>()
{
new UserButtons() { Button1="UserButton1", Button2 = "UserButton2"},
new UserButtons() { Button1="Cheese", Button2 = "Wine"},
new UserButtons() { Button1="Wallace", Button2 = "Gromit"},
};
this.itemsControl.ItemsSource = oc;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
oc.Add(new UserButtons() { Button1 = "NewButton1", Button2 = "NewButton2" });
}
}
public class UserButtons : INotifyPropertyChanged
{
private string button1;
public string Button1
{
get { return this.button1; }
set
{
this.button1 = value;
this.OnPropertyChanged("Button1");
}
}
private string button2;
public string Button2
{
get { return this.button2; }
set
{
this.button2 = value;
this.OnPropertyChanged("Button2");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
#endregion
}