【问题标题】:What is the correct way to bind a DataGrid to XML in MVVM?在 MVVM 中将 DataGrid 绑定到 XML 的正确方法是什么?
【发布时间】:2020-02-06 19:57:50
【问题描述】:

我想将 DataGrid 绑定到一个 XML 文件,该文件可以通过双向绑定进行更新/更改。

目前,更新时源不会改变。

我尝试使用以下代码构建它:

XAML

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding CFCCDataView.DataView, UpdateSourceTrigger=PropertyChanged}"/>

视图模型

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

<?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>

【问题讨论】:

    标签: c# xml wpf xaml binding


    【解决方案1】:

    你应该添加 DataCntext 来查看它知道从哪里获取数据,

    在您的 xaml.cs 中:

       public partial class MainWindow : Window
    {
        private readonly ViewModel viewModel = new ViewModel();
        public MainWindow()
        {
            DataContext = viewModel;
            InitializeComponent();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-13
      • 2018-03-01
      • 2013-03-24
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      相关资源
      最近更新 更多