C# 在MVVM中,将DataGrid绑定到XML的正确方法是什么?
我想将DataGrid绑定到XML文件,该文件可以通过双向绑定进行更新/更改 当前,源在更新时不会更改 我尝试使用以下代码构建它: XAML 模型 XMLC# 在MVVM中,将DataGrid绑定到XML的正确方法是什么?,c#,xml,wpf,xaml,binding,C#,Xml,Wpf,Xaml,Binding,我想将DataGrid绑定到XML文件,该文件可以通过双向绑定进行更新/更改 当前,源在更新时不会更改 我尝试使用以下代码构建它: XAML 模型 XML 您应该将DataCntext添加到视图中,因为它知道从何处获取数据 在您的xaml.cs中: public partial class MainWindow : Window { private readonly ViewModel viewModel = new ViewModel(); public MainWind
您应该将DataCntext添加到视图中,因为它知道从何处获取数据 在您的xaml.cs中:
public partial class MainWindow : Window
{
private readonly ViewModel viewModel = new ViewModel();
public MainWindow()
{
DataContext = viewModel;
InitializeComponent();
}
}
public XMLCFCCTranslationList CFCCDataView { get; set; }
public VM()
{
CFCCDataView = new XMLCFCCTranslationList();
}
class XMLCFCCTranslationList : INotifyPropertyChanged
{
private void RaisePropertyChanged(string prop)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
private DataView _dataView;
public DataView DataView
{
get => _dataView;
set
{
if (_dataView == value) return;
_dataView = value;
RaisePropertyChanged("DataView");
}
}
public XMLCFCCTranslationList()
{
var dataSet = new DataSet();
dataSet.ReadXml(@"c:\file.xml");
var cfccDataView = new DataView(dataSet.Tables[0]);
DataView = cfccDataView;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<Translation xmlns="">
<CFCCTranslation CFCC="A10" FUNC_CLASS="1" SPEED_CAT="5" />
<CFCCTranslation CFCC="A20" FUNC_CLASS="2" SPEED_CAT="5" />
<CFCCTranslation CFCC="A30" FUNC_CLASS="3" SPEED_CAT="5" />
<CFCCTranslation CFCC="A40" FUNC_CLASS="4" SPEED_CAT="5" />
<CFCCTranslation CFCC="A50" FUNC_CLASS="5" SPEED_CAT="5" />
<CFCCTranslation CFCC="A71" FUNC_CLASS="6" SPEED_CAT="5" />
<CFCCTranslation CFCC="B10" FUNC_CLASS="7" SPEED_CAT="5" />
</Translation>
public partial class MainWindow : Window
{
private readonly ViewModel viewModel = new ViewModel();
public MainWindow()
{
DataContext = viewModel;
InitializeComponent();
}
}