[英]Binding DataTable to DataGrid C# WPF MVVM
MVVM的新增功能,試圖找出將動態生成的DataTable與DataGrid綁定時出了錯的地方。 我找到了一些解決方案,並嘗試根據以前的響應對我的實現進行調整:
XAML:
<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding dataTable, Mode=TwoWay}" AutoGenerateColumns="False" VerticalAlignment="Center">
<DataGrid.Columns>
<DataGridTextColumn Header="Header1" Binding="{Binding Column1Name}"/>
<DataGridTextColumn Header="Header2" Binding="{Binding Column2Name}"/>
</DataGrid.Columns>
<DataGrid.DataContext>
<ViewModels:Presenter/>
</DataGrid.DataContext>
XAML CS:
DataTable dataTable = new DataTable();
Grid.DataContext = dataTable.DefaultView;
//I don't believe I should be using System.Data in View?
視圖模型
。主持人:
public class Presenter : ObservableObject {
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set
{
_dataTable = value;
RaisePropertyChangedEvent("Grid");
}
}
private void ParseData()
{
if (string.IsNullOrWhiteSpace(ID)) return;
dataTable = DataParser.ParseURL(ID);
}
}
.ObservableObject
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我知道模型中的數據可以正確返回,並且當我在調試器中時,會觸發RaisePropertyChangedEvent,但視圖未更新。
您提出了錯誤的PropertyName
(它似乎是XAML中Grid
的名稱)。
調用RaisePropertyChanged
方法時,請提高名稱"dataTable"
。
像這樣:
public DataTable dataTable
{
get { return _dataTable; }
set
{
_dataTable = value;
RaisePropertyChangedEvent("dataTable");
}
}
您可以做的其他一些事情是:
propertyName
參數之前使用[CallerMemberName]
屬性。 這將省去您提供它的protected void RaisePropertyChangedEvent([CallerMemberName] string propertyName)
,因為它可以檢測到調用它的屬性(C#5及更高版本)-例如: protected void RaisePropertyChangedEvent([CallerMemberName] string propertyName)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
在您的RaisePropertyChanged
方法中。 這省去了創建變量並檢查是否為null
(C#6及更高版本) dataTable
屬性重命名為DataTable
可以更清楚地了解什么是屬性和什么是字段,這在C#中是很平常的事情 希望這可以幫助 :)
由於您將DataGrid
的DataContext
設置為DataTable
的DataView
,如下所示:
Grid.DataContext = dataTable.DefaultView;
...您應該直接綁定到DataContext
:
<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalAlignment="Center">
...
如果要綁定到dataTable
屬性,則應將DataContext
設置為Presenter
類的實例:
var p = new Presenter();
Grid.DataContext = p;
<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding dataTable}" AutoGenerateColumns="False" VerticalAlignment="Center">
然后,可以將Presenter
對象的dataTable
屬性設置為新的DataTable
:
p.dataTable = new DataTable();
您仍然需要按照@Geoff James的建議修改屬性:
public DataTable dataTable
{
get { return _dataTable; }
set
{
_dataTable = value;
RaisePropertyChangedEvent("dataTable");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.