【问题标题】:Textblock in a listview doesn't show the bind data - WPF XAML列表视图中的文本块不显示绑定数据 - WPF XAML
【发布时间】:2018-06-10 22:39:52
【问题描述】:

我正在尝试将数据与列表视图中的文本块绑定,但它不显示数据。但是,当我运行应用程序时,我可以看到列表已创建,但显示的是空数据。请参阅下图中的空数据列表:


这是我的 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;

请帮我弄清楚我在哪里犯了错误。任何帮助将不胜感激。谢谢

阿里

【问题讨论】:

    标签: wpf xaml listview mvvm data-binding


    【解决方案1】:

    经过几个小时的研究,我意识到我的代码存在一些问题。解决方案是首先在 WPF Form 构造方法中定义数据上下文,即

    listView_attachedFiles.DataContext = ListofViewModel; 
    

    第二次更新这个 XAML 代码

    <TextBlock Width="100" Text="{Binding AttachedFiles, Mode=TwoWay, NotifyOnTargetUpdated=True}">
    

    使用此 XAML 代码。

    <TextBlock Width="100" Text="{Binding}">
    

    现在保存,构建应用程序,运行它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多