我遇到的問題是這樣的:我有WPF ListView綁定到實現INotifyPropertyChanged接口的對象的ObservableCollection。在我的屬性設置器中,我做了一些數據驗證,並且在用戶輸入無效數據的情況下,我將彈出一個消息框並將該屬性設置爲默認值。目前這一切正常。問題是,如果通過ListView中的用戶輸入更新屬性,如果用戶在屬性更新爲默認值時輸入「無效」數據,則ListView未更新以反映該問題ListView不更新如果基礎數據正在由ListView更新
例如,根據下面的代碼,如果用戶輸入設備ID列的字母'a',它們將彈出,並且該屬性將被設置爲-1,但ListView將繼續顯示'a'。
的XAML 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 */
}
這一切看起來一見鍾情很確定。當您使用null調用NotifyPropertyChanged時會發生什麼?這必須刷新整個對象實例。並在吸氣劑處設置一個斷點,看看它是否在某些點被調用。 PageLoad,編輯屬性等。 –
我建議您查看IDataErrorInfo接口以及如何將其用於WPF數據驗證。這裏有一個很好的教程:http://tarundotnet.wordpress.com/2011/03/03/wpf-tutorial-how-to-use-idataerrorinfo-in-wpf/ –
什麼版本的.NET?我有一個簡單的文本框的問題。去.NET 4.5修復它。但是我目前遇到了ComboBox SelectedIndex的問題。這就像UI元素決定它知道更好並忽略獲得。 – Paparazzi