如果ListView正在更新基础数据,则ListView不会更新

时间:2014-06-16 14:21:51

标签: c# wpf listview

我遇到的问题是:我有WPF ListView绑定到实现INotifyPropertyChanged接口的ObservableCollection对象。在我的属性的setter中,我做了一些数据验证,在用户输入无效数据的情况下,我会弹出一个消息框并将属性设置为默认值。目前这一切都在运作。问题是,如果通过ListView中的用户输入更新属性,则用户输入"无效"数据在属性确实更新为默认值时,ListView未更新以反映

例如,根据下面的代码,如果用户要输入字母' a'对于设备ID列,它们将弹出,属性将设置为-1,但ListView将继续显示' a'。

ListView的XAML:

<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 */
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解您的问题,但_DeviceID必须是公共属性并实现PropertyChanged才能让UI反映对其所做的任何更改。

所以将属性更改为

private int _DeviceID;
public int DeviceID
    {
        get
        {

          return _DeviceID;

        }

        set
        {
          _DeviceID = value;
          OnPropertyChanged("DeviceID");
        }