我的建议是在您的 Window 之外创建一个类,该类负责将数据提供给您的ListBox
. 一种常见的方法是 WPF 称为MVVM,它像任何模式一样有许多实现。
基础是每个模型(例如Pound
和Dog
)都有一个视图模型,负责以一种易于从 UI 交互的方式呈现模型。
为了帮助您入门,WPF 提供了一个出色的类 ,ObservableCollection<T>
它是一个集合,每当添加、移动或删除任何人时都会触发“Hey I Changed”事件。
下面是一个不打算教你 MVVM 的例子,也没有使用任何 MVVM 框架。但是,如果您设置一些断点并使用它,您将了解绑定、命令、INotifyPropertyChanged 和 ObservableCollection;所有这些都在 WPF 应用程序开发中发挥着重要作用。
从 开始MainWindow
,您可以将您的设置DataContext
为视图模型:
public class MainWindow : Window
{
// ...
public MainWindow()
{
// Assigning to the DataContext is important
// as all of the UIElement bindings inside the UI
// will be a part of this hierarchy
this.DataContext = new PoundViewModel();
this.InitializeComponent();
}
}
管理对象PoundViewModel
集合的位置DogViewModel
:
public class PoundViewModel
{
// No WPF application is complete without at least 1 ObservableCollection
public ObservableCollection<DogViewModel> Dogs
{
get;
private set;
}
// Commands play a large role in WPF as a means of
// transmitting "actions" from UI elements
public ICommand AddDogCommand
{
get;
private set;
}
public PoundViewModel()
{
this.Dogs = new ObservableCollection<DogViewModel>();
// The Command takes a string parameter which will be provided
// by the UI. The first method is what happens when the command
// is executed. The second method is what is queried to find out
// if the command should be executed
this.AddDogCommand = new DelegateCommand<string>(
name => this.Dogs.Add(new DogViewModel { Name = name }),
name => !String.IsNullOrWhitespace(name)
);
}
}
在您的 XAML 中(一定要映射xmlns:local
以允许 XAML 使用您的视图模型):
<!-- <Window ...
xmlns:local="clr-namespace:YourNameSpace" -->
<!-- Binding the ItemsSource to Dogs, will use the Dogs property
-- On your DataContext, which is currently a PoundViewModel
-->
<ListBox x:Name="listBox1"
ItemsSource="{Binding Dogs}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:DogViewModel}">
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="5">
<TextBox Text="{Binding Name}" />
</Border>
</DataTemplate>
</ListBox.Resources>
</ListBox>
<GroupBox Header="New Dog">
<StackPanel>
<Label>Name:</Label>
<TextBox x:Name="NewDog" />
<!-- Commands are another big part of WPF -->
<Button Content="Add"
Command="{Binding AddDogCommand}"
CommandParameter="{Binding Text, ElementName=NewDog}" />
</StackPanel>
</GroupBox>
当然,你需要一个DogViewModel
:
public class DogViewModel : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
// Needed to alert WPF to a change in the data
// which will then update the UI
this.RaisePropertyChanged("Name");
}
}
public event PropertyChangedHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
最后你需要一个实现DelegateCommand<T>
:
public class DelegateCommand<T> : ICommand
{
private readonly Action<T> execute;
private readonly Func<T, bool> canExecute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<T> execute, Func<T, bool> canExecute)
{
if (execute == null) throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(T parameter)
{
return this.canExecute != null && this.canExecute(parameter);
}
bool ICommand.CanExecute(object parameter)
{
return this.CanExecute((T)parameter);
}
public void Execute(T parameter)
{
this.execute(parameter);
}
bool ICommand.Execute(object parameter)
{
return this.Execute((T)parameter);
}
}
这个答案决不会让您获得身临其境的、完全绑定的 WPF UI,但希望它能让您了解 UI 如何与您的代码交互!