我有一个绑定(bind)到 observablecollection 的文本框,当我更新元素(通过拖放触发 View 文件中处理的事件)时,文本框不会更新其值。但是,数据会添加到放置时的可观察集合中,如果我刷新数据(通过实际选择列表框中的不同项目并切换回当前记录),数据就会出现。
我已阅读: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>
这是我的事件代码,用于处理用户控件在 View 文件中的放置。
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);
}
}
}
我添加到集合中的事实是否足以更新绑定(bind)到 observablecollection 的文本框,或者我是否遗漏了一些非常明显的东西?
最佳答案
本质上,TextBox
无法知道绑定(bind)到 Text
的集合已更新。由于 Text
属性不监听 CollectionChanged
事件,因此更新 ObservableCollection
也将被忽略,正如@Clemens 所指出的。
在您的 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));
}
}
关于c# - 绑定(bind)到 ObservableCollection 的 TextBox 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34809465/