在运行时将数据表绑定到 WPF MVVM 中的数据网格

本文关键字:数据 数据网 网格 MVVM WPF 运行时 数据表 绑定 | 更新日期: 2023-09-27 18:31:04

我正在开发一个具有 MVVM 设计模式的 WPF 应用程序,在我的第一个窗口中,我想显示使用文本框的选定文本创建的数据网格 这是我想做的预览

在我的 ViewModel 中,我实现了一个方法,该方法用 selectedText 填充数据表,然后将其绑定到 DataGrid,但我的数据网格不显示任何内容。这是我的方法

 void selectColumn(object parameter)
{
    string selText = SelectedText;
    if (i == 0)
    {
        var lines = File.ReadAllLines(TextProperty1);
        datatable.Columns.Add("Column" + i + "");
        foreach (string line in lines)
        {
            DataRow newRow = datatable.NewRow();
            newRow["Column" + i + ""] = line.Substring(0, selText.Length);
            datatable.Rows.Add(newRow)
        }
        i++;
    }
    else
    {
        datatable.Columns.Add("Column" + i + "");
        var lines = File.ReadAllLines(TextProperty1);
        foreach (DataRow draw in datatable.Rows)
        {
            draw["Column" + i + ""] = lines[datatable.Rows.IndexOf(draw)].Substring(lines[2].IndexOf(selText), selText.Length);
        }
        TblData2 = datatable;
        i++;
    }
    TblData2 = datatable;
    TextProperty2 = TextProperty2.Remove(0, selText.Length);
}

在窗口中,这就是我绑定数据网格的方式

<TextBox x:Name="txt" Text="{Binding TextProperty2, UpdateSourceTrigger=PropertyChanged}">
        <i:Interaction.Behaviors>
            <i:DependencyPropertyBehavior PropertyName="SelectedText" EventName="SelectionChanged" Binding="{Binding SelectedText, Mode=TwoWay}"/>
        </i:Interaction.Behaviors>
    </TextBox>
    <Button x:Name="Tex"  Content="Select Column" Command="{Binding SelectedColumnCommand}"/>
    <DataGrid x:Name="DtGrid"  ItemsSource="{Binding TblData2}"/>

这是数据表

DataTable _dataTable2;
    public DataTable TblData2
    {
        get { return _dataTable2; }
        set
        {
            _dataTable2 = value;
            RaisePropertyChanged("TblData");
        }
    }

在运行时将数据表绑定到 WPF MVVM 中的数据网格

尝试在 ViewModel 中输入以下代码。

1.添加包含所有选定文本的可观察集合属性

ObservableCollection<string> _SelectedTexts; 
public ObservableCollection<string> SelectedTexts
{
    get { return _SelectedTexts; }
    set
    {
       _SelectedTexts; = value;
       RaisePropertyChanged("SelectedTexts");
    }
} 
public YourViewModelConstructor
{
    SelectedTexts = new ObservableCollection<string>();
}

2.在可观察收藏中添加所选文本

public void AddSelectedText(string selectedText)
{
     SelectedTexts.Add(selectedText);

}

3.XAML数据绑定

<DataGrid x:Name="DtGrid"  ItemsSource="{Binding SelectedTexts}"/>

我没有检查所有代码,但是将 ItemsSource 绑定到某个属性,然后在运行时更改该属性将不起作用,您将不得不使用 ObservableCollection。希望对您有所帮助。