首先,我想和大家打个招呼,因为这是我在这里的第一篇文章。
这是我在WPF中的第一个项目,我的ListBox中的项目几乎没有问题 - 当我从反序列化的XML中将它们添加为Listbox.ItemsSource时,它们并不令人耳目一新。我已经实现了INotifyPropertyChanged接口,但仍然缺少一些东西。
这是ListBox声明:
<ListBox x:Name="lstbRealmlist" Grid.ColumnSpan="2" Grid.Row="1" Width="160" Height="220" Margin="10,0" HorizontalAlignment="Left" VerticalAlignment="Center" ItemContainerStyle="{StaticResource ListboxItemStyle}">
<ListBox.Background>
<ImageBrush ImageSource="/SunwellLauncher;component/Images/content-bg.jpg" Stretch="UniformToFill" TileMode="None" />
</ListBox.Background>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="#FFBA7C0E" Margin="1" CornerRadius="3" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Label Content="{Binding name}" FontSize="16"/>
<Label Content="{Binding website}" Grid.Row="1"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Realmlists和Realm类:
namespace SunwellLauncher
{
[XmlRoot("Realmlists"), Serializable]
public class Realmlists : INotifyPropertyChanged
{
private ObservableCollection<Realm> realm;
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("Realm")]
public ObservableCollection<Realm> Realm
{
get { return realm; }
set
{
realm = value;
OnPropertyChanged("Realm");
}
}
#region Constructors
public Realmlists()
{
}
public Realmlists(ObservableCollection<Realm> value)
{
this.realm = value;
}
#endregion
protected void OnPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
public class Realm
{
[XmlElement("name")]
public string name { get; set; }
[XmlElement("address")]
public string address { get; set; }
[XmlElement("website")]
public string website { get; set; }
}
}
和方法将XML反序列化为Realmlists对象并填充ListBox:
public void ListItemsAddFromXML(XDocument doc)
{
XmlSerializer reader = new XmlSerializer(typeof(Realmlists));
Realmlists realmlists = (Realmlists)reader.Deserialize(doc.CreateReader());
lstbRealmlist.ItemsSource = realmlists.Realm;
}
在应用程序启动时,此方法从XML文件填充ListBox,这工作正常但问题是当我尝试使用它来更新它时 - 没有任何反应。在其他窗口中,我正在更新该XML文件,等到更改(XMLsave)并再次运行此方法来更新Listbox。当通过委托完成xml更改时,从FileSystemWatcher调用方法。
private void CreateWatcher()
{
watcher = new FileSystemWatcher();
watcher.Filter = "Realmlists.xml";
watcher.Changed += watcher_FileChanged;
watcher.Path = mw.path;
watcher.EnableRaisingEvents = true;
}
void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
Dispatcher.Invoke(DispatcherPriority.Normal, new MainWindow.ListItemsAdd(mw.ListItemsAddFromXML), doc);
watcher.EnableRaisingEvents = false;
watcher.Created -= watcher_FileChanged;
watcher.Dispose();
}
我还在Realmlists定义中将List更改为ObservableCollection。
我犯了哪个错误?
答案 0 :(得分:1)
您需要使用Xaml中的Binding表达式将Listbox ItemSource绑定到Realmlist。目前,您正在实例化列表并在后面的代码中设置ItemSource。