我已经这么多次这样做了,但这让我很难过。
public class ObservableObject : System.ComponentModel.INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(Object PropertyValue)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(PropertyValue.ToString()));
}
}
}
简单的通知属性已更改。
非常简单的自定义类对象
class Device : ObservableObject
{
public String DeviceName
{
get { return _DeviceName; }
set { _DeviceName = value; NotifyPropertyChanged("DeviceName"); }
}
private String _DeviceName = "";
public Device() { }
public Device(String ComputerName)
{
DeviceName = ComputerName;
}
}
视图模型
class MainWindowViewModel :ObservableObject
{
public Device SelectedDevice { get; set; }
public List<Device> DeviceList
{
get { return _DeviceList; }
set { _DeviceList = value; NotifyPropertyChanged("DeviceList"); }
}
public List<Device> _DeviceList = new List<Device>();
public MainWindowViewModel()
{
CreateDelegateCommands();
DeviceList.Add(new Device("Metabox-PC"));
DeviceList.Add(new Device("NewPC"));
DeviceList.Add(new Device("OldPC"));
}
#region Delegated Commands
public Boolean CreateDelegateCommands()
{
try
{
ContextMenuCommand = new DelegateCommand(DelegatedContextMenuCommand);
return true;
}
catch
{
return false;
}
}
public DelegateCommand ContextMenuCommand { get; set; }
public void DelegatedContextMenuCommand(Object Parameter)
{
System.Windows.Controls.MenuItem MenuItemClicked = Parameter as System.Windows.Controls.MenuItem;
switch (MenuItemClicked.Header.ToString())
{
case "Delete": { DeviceList.Remove(SelectedDevice); NotifyPropertyChanged("DeviceList"); break; }
}
}
#endregion
}
查看
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="102*"/>
<ColumnDefinition Width="415*"/>
</Grid.ColumnDefinitions>
<ListView ItemsSource="{Binding DeviceList}" SelectedItem="{Binding SelectedDevice,Mode=TwoWay}">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Command="{Binding ContextMenuCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Header="Device" DisplayMemberBinding="{Binding DeviceName}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
简单地说,右键单击我放入List<T>
的其中一个测试对象,然后单击“删除”。这项工作并触发委托命令,
该命令然后处理好和NotifyPropertyChanged(T)触发器。没有任何错误,但是我的视图仍然显示相同的三个对象。但在视图模型中,List<T>
仅显示2个对象。
我哪里出错?
答案 0 :(得分:2)
我想你应该试试
public ObservableCollection<Device> DeviceList
{
get { return _DeviceList; }
set { _DeviceList = value; NotifyPropertyChanged("DeviceList"); }
}
public ObservableCollection<Device> _DeviceList = new ObservableCollection<Device>();