![](/img/trans.png)
[英]INotifyPropertyChanged won't update a property if only the properties' elements changed
[英]INotifyPropertyChanged won't update the view
我已經做過很多次了,但這讓我很困惑。
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個對象。
我哪里出問題了?
我認為你應該嘗試
public ObservableCollection<Device> DeviceList
{
get { return _DeviceList; }
set { _DeviceList = value; NotifyPropertyChanged("DeviceList"); }
}
public ObservableCollection<Device> _DeviceList = new ObservableCollection<Device>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.