【发布时间】:2016-02-07 17:48:46
【问题描述】:
我正在开发一个小型 WPF 应用程序,我想向用户提供一个字符串列表,用户可以对其进行编辑、添加或删除。
我做的第一件事是创建一个带有视图模型更改通知的基类:
public abstract class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在此之后,我为绑定/更改通知的字符串创建了一个包装器:
public class StringViewModel : BaseViewModel
{
private string value;
public string Value
{
get { return this.value; }
set
{
if (value == this.value) return;
this.value = value;
this.RaisePropertyChanged(nameof(this.Value));
}
}
}
然后我有一个使用这个类的视图模型(我省略了其他不相关的成员):
public class UserSettingsDataViewModel : BaseViewModel
{
private ObservableCollection<StringViewModel> blacklistedFiles;
public ObservableCollection<StringViewModel> BlacklistedFiles
{
get { return this.blacklistedFiles; }
set
{
if (Equals(value, this.blacklistedFiles)) return;
this.blacklistedFiles = value;
this.RaisePropertyChanged(nameof(this.BlacklistedFiles));
}
}
}
最后,我将这个包含在我的 XAML 中,用于相关屏幕:
<WrapPanel>
<Label>Blacklisted files</Label>
<DataGrid ItemsSource="{Binding Data.BlacklistedFiles}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Value}" Header="File name" />
<DataGridTemplateColumn Header="Remove">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Remove" Command="Delete" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</WrapPanel>
一切正常,除了我无法编辑新成员或现有成员的值。我可以点击单元格并让它进入编辑模式模式,但是按键没有任何作用(除了我似乎能够添加或删除空格)。我觉得必须有一个直截了当的解决方法,但它让我望而却步。
【问题讨论】: