我尝试将数据与listview中的文本块绑定,但它没有显示数据。但是,当我运行应用程序时,我可以看到列表已创建,但它显示空数据。请参阅下图中的空白数据列表:
这是我的XAML代码:
<ListView Margin="20,0,0,20" x:Name="listView_attachedFiles">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Width="100" Text="{Binding AttachedFiles, Mode=TwoWay, NotifyOnTargetUpdated=True}">
<Hyperlink>
</Hyperlink>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
这里是C#代码
public class ListviewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _attachedfiles;
public ObservableCollection<string> AttachedFiles
{
get { return _attachedfiles; }
set
{
_attachedfiles = value;
OnPropertyChanged("AttachedFiles");
}
}
public ListviewModel()
{
AttachedFiles = new ObservableCollection<string>();
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
以下是我填充数据的方式:
// I'm calling this method to attach the list of filenames
private void ExecuteMethod_AttachFile(object Parameter)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == true)
{
AttachedFileLocation = ofd.FileNames.ToList();
// adding bind data to the list of viewmodel: adding attachefile names
foreach (var file in AttachedFileLocation)
{
FileInfo info = new FileInfo(file);
DMS_Form.Instance.ListofViewModel.AttachedFiles.Add(info.Name + " X");
}
}
}
这是我如何在WPF表单的构造函数中附加itemssource引用。
//Binding the list of attached files with the listview
listView_attachedFiles.ItemsSource = ListofViewModel.AttachedFiles;
请帮我弄清楚我犯了哪些错误。任何帮助将受到高度赞赏。谢谢
阿里
答案 0 :(得分:0)
通过几个小时的研究,我意识到我的代码有点问题。解决方案是首先在WPF表单构造函数方法中定义数据上下文,即
listView_attachedFiles.DataContext = ListofViewModel;
第二次更新此XAML代码
<TextBlock Width="100" Text="{Binding AttachedFiles, Mode=TwoWay, NotifyOnTargetUpdated=True}">
使用此XAML代码。
<TextBlock Width="100" Text="{Binding}">
现在保存,然后构建应用程序,运行它。