[英]TextBox bound to ObservableCollection not updating
我有一個綁定到observablecollection的文本框,當我更新元素時(通過拖放觸發觸發在視圖文件中處理的事件),該文本框不會更新其值。 但是,數據將被添加到下拉列表中的可觀察集合中,並且如果我刷新數據(實際上是通過在列表框中選擇其他項並切換回當前記錄)來顯示數據。
我已閱讀: http : //updatecontrols.net/doc/tips/common_mistakes_observablecollection ,不,我不相信我會覆蓋該收藏!
<StackPanel>
<TextBox Text="{Binding Path=ImageGalleryFilenames, Converter={StaticResource ListToStringWithPipeConverter}}" Height="41" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Button Height="25" Margin="0 2" AllowDrop="True" Drop="HandleGalleryImagesDrop">
<TextBlock Text="Drop Image Files Here"></TextBlock>
</Button>
</StackPanel>
這是我的事件代碼,用於處理用戶控件在視圖文件中的刪除。
private void HandleGalleryImagesDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (var fn in filenames)
{
this.vm.CurrentSelectedProduct.ImageGalleryFilenames.Add(fn);
}
}
}
我添加到集合中的事實不足以更新綁定到observablecollection的文本框的事實,還是我錯過了令人眼花obvious亂的明顯東西?
從本質上講, TextBox
不可能知道綁定到Text
的集合已被更新。 由於Text
屬性不偵聽CollectionChanged
事件,因此@Clemens指出的更新ObservableCollection
也將被忽略。
在您的ViewModel中,這是一種實現方法。
private ObservableCollection<ImageGalleryFilename> _imageGalleryFilenames;
public ObservableCollection<ImageGalleryFilename> ImageGalleryFilenames
{
get
{
return _imageGalleryFilenames;
}
set
{
_imageGalleryFilenames= value;
if (_imageGalleryFilenames!= null)
{
_imageGalleryFilenames.CollectionChanged += _imageGalleryFilenames_CollectionChanged;
}
NotifyPropertyChanged("ImageGalleryFilenames");
}
}
private void _imageGalleryFilenames_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
NotifyPropertyChanged("ImageGalleryFilenames");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.