如果底层数据正在被ListView更新,ListView不会更新
本文关键字:更新 ListView 数据 如果 | 更新日期: 2023-09-27 18:08:53
我遇到的问题是:我有WPF ListView,它绑定到实现INotifyPropertyChanged接口的对象的ObservableCollection。在属性的setter中,我做了一些数据验证,在用户输入无效数据的情况下,我会弹出一个消息框,并将属性设置为默认值。目前这一切都在工作。问题是,如果属性通过用户输入在ListView中更新,如果用户输入"无效"数据,而属性确实被更新为默认值,ListView不会更新以反映
例如,给出下面的代码,如果用户要为设备ID列输入字母'a',他们将得到一个弹出窗口,属性将被设置为-1,但ListView将继续显示'a'。
XAML for ListView:<ListView Margin="0,0,0,0" Name="configListView" SelectionMode="Single" ItemsSource="{Binding Path=''}" IsSynchronizedWithCurrentItem="True">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<EventSetter Event="GotFocus" Handler="EditItemGotFocusDelegate"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Device ID" Width="75">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=DeviceID}" Margin="-6,0,-6,0"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<!-- More Columns declared just like above -->
</GridView>
</ListView.View>
</ListView>
属性代码如下:
class ConfigItem : INotifyPropertyChanged
{
private int _DeviceID = -1;
/* More variables...*/
/* Implementation of INotifyPropertyChanged */
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
/* Property definition */
public string DeviceID
{
get
{
if (_DeviceID == -1)
{
return "<Default>";
}
else
{
return _DeviceID.ToString();
}
}
set
{
if (value == "")
{
_DeviceID = -1;
}
else if(int.TryParse(value, out _DeviceID) == false || _DeviceID > 1023 || _DeviceID < 0)
{
System.Windows.MessageBox.Show("Device ID must be a number greater than 0 and less than 1024");
_DeviceID = -1;
}
NotifyPropertyChanged("DeviceID");
}
}
/* More Properties definitions exactly as above */
}
我不确定我是否正确理解你的问题,但_DeviceID必须是一个公共属性,并实现PropertyChanged,以便让UI反映对它所做的任何更改。
将属性改为
private int _DeviceID;
public int DeviceID
{
get
{
return _DeviceID;
}
set
{
_DeviceID = value;
OnPropertyChanged("DeviceID");
}