我正在使用 MVVM 设计模式开发 WPF 应用程序,在我的第一个窗口中,我想显示一个数据网格,该数据网格是使用文本框的选定文本创建的 This is a preview of what i want to do
在我的 ViewModel 中,我实现了一种方法,该方法使用 selectedText 填充数据表,然后将其绑定(bind)到 DataGrid,但我的 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);
}
在 Window 中,这就是我绑定(bind) Datagrid 的方式
<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");
}
}
最佳答案
尝试在您的 ViewModel 中输入以下代码。
1.添加一个包含所有选中文本的 ObservableCollection 属性
ObservableCollection<string> _SelectedTexts;
public ObservableCollection<string> SelectedTexts
{
get { return _SelectedTexts; }
set
{
_SelectedTexts; = value;
RaisePropertyChanged("SelectedTexts");
}
}
public YourViewModelConstructor
{
SelectedTexts = new ObservableCollection<string>();
}
2.在ObservableCollection中添加选中的文本
public void AddSelectedText(string selectedText)
{
SelectedTexts.Add(selectedText);
}
3.xaml数据绑定(bind)
<DataGrid x:Name="DtGrid" ItemsSource="{Binding SelectedTexts}"/>
关于c# - 在运行时将 DataTable 绑定(bind)到 WPF MVVM 中的 Datagrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897852/