将数据表绑定到MVVM WPF中的datagrid [英] Binding datatable to datagrid in MVVM WPF

查看:83
本文介绍了将数据表绑定到MVVM WPF中的datagrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML,里面有一些音乐信息。我正在通过ReadXml方法将我的XML读取到DataSet。然后创建一个DataTable并获取DataSet的第一个表信息,我试图将DataTable绑定到MVVM模式中的DataGrid。下面是我的MainWindow视图:将我的ViewModel绑定到MainWindow DataContext



I have an XML which has some music info in it. I'm reading my XML to DataSet through ReadXml method. Then creating a DataTable and getting the 1st table info of DataSet and I'm trying to bind DataTable to DataGrid in MVVM Pattern. Below is my MainWindow View: Binding my ViewModel to MainWindow DataContext

<Grid>
        <View:XElementV/>
        <View:XElementV DataContext="{Binding XElementVM}"/>
    </Grid>





MainWindow.Xaml.cs:将VM分配为datacontext



MainWindow.Xaml.cs : Assigning VM as datacontext

public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new XElementVM();
        }  





XElementV.Xaml:



XElementV.Xaml :

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>

        <DataGrid ItemsSource="{Binding Path=DataTableObject, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True"  CanUserAddRows="True" CanUserDeleteRows="False" IsReadOnly="True">
            <DataGrid.Columns>
                <DataGridTemplateColumn Width="25">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <RadioButton HorizontalAlignment="Center" GroupName="Trail"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>    
        </DataGrid>
        <Button Grid.Row="1" VerticalAlignment="Center" Height="20" Content="Sample Button" HorizontalAlignment="Right" Margin="0,0,20,0"/>
    </Grid>





XElementVM.cs





XElementVM.cs

public XElementVM()
        {
            XmlTextReader xmlContent = new XmlTextReader(@"Music.xml");
            DataSet tableSet = new DataSet();
            tableSet.ReadXml(xmlContent);
            DataTableObject = tableSet.Tables[0];            
        }  




When debugged the code, I'm able to get the XML data into the datatable but I'm unable to bind the data to UI. What might be the problem. Thank you.





编辑:Xml



Edit : Xml

<Music>
  <Album Title="Chris Sells Live" Artist="Chris Sells" ReleaseDate="2/5/2008" /> 
  <Album Title="The Road to Redmond" Artist="Luka Abrus" ReleaseDate="4/3/2008" /> 
  <Album Title="The Best of Jim Hance" Artist="Jim Hance" ReleaseDate="6/2/2008" /> 
</Music>





我的尝试:



我上面发布的代码是我试过的。



What I have tried:

What ever the code which I have posted above is what I have tried.

推荐答案

参考下面的函数,它添加了DataGridTextColumn dy​​n

Hi, refer the below function, it adds DataGridTextColumn dyn
private void SetColumnsAndBinding(DataTable objTable)
{
    DataGridTemplateColumn objRadioButtonColumn = new DataGridTemplateColumn();
    DataTemplate RadioButtonCellTemplate = new DataTemplate();

    FrameworkElementFactory objRadButtonColumnFactory = new FrameworkElementFactory(typeof(RadioButton));
    objRadioButtonColumn.SetValue(RadioButton.GroupNameProperty, "Trial");
    RadioButtonCellTemplate.VisualTree = objRadButtonColumnFactory;
    objRadioButtonColumn.CellTemplate = RadioButtonCellTemplate;

    YourDataGrid.Columns.Add(objRadioButtonColumn);

    foreach (DataColumn objColumn in objTable.Columns)
    {
        DataGridTextColumn objDgridColumn = new DataGridTextColumn();
        objDgridColumn.Header = objColumn.ColumnName;

        Binding objBinding = new Binding();
        objBinding.Path = new PropertyPath(objColumn.ColumnName);

        objDgridColumn.Binding = objBinding;

        YourDataGrid.Columns.Add(objDgridColumn);
    }
}



此函数在datagrid中添加 DataGridTemplateColumn 以显示单选按钮。它根据DataTable中存在的列添加 DataGridTextColumn 对象,该列从XML文件中读取。这很有效。但它违反了MVVM原则。为了在MVVM中使用这种技术,我做了以下工作,

1.在ViewModel中声明 DataGridColumn ObservableCollection 来保存列像这样的集合,


This function adds a DataGridTemplateColumn in datagrid to show radiobutton. And it adds DataGridTextColumn objects based on the columns present in the DataTable, which is read from XML file. This is working. But it violates MVVM principle. In order to use this technique in MVVM, I did the following,
1. Declaring an ObservableCollection of DataGridColumn in the ViewModel to hold the columns collection, like this,

private ObservableCollection<DataGridColumn> _CustomColumns = new ObservableCollection<DataGridColumn>();

public ObservableCollection<DataGridColumn> CustomColumns
{
    get { return _CustomColumns; }
    set
    {
        _CustomColumns = value;
        OnPropertyChanged("CustomColumns");
    }
}



只需修改上述功能,我就可以像这样在上面的集合中添加列,


By just modifying the above function, I can add columns to above collection like this,

private void SetColumnsAndBinding(DataTable objTable)
{
    DataGridTemplateColumn objRadioButtonColumn = new DataGridTemplateColumn();
    DataTemplate RadioButtonCellTemplate = new DataTemplate();

    FrameworkElementFactory objRadButtonColumnFactory = new FrameworkElementFactory(typeof(RadioButton));
    objRadioButtonColumn.SetValue(RadioButton.GroupNameProperty, "Trial");
    RadioButtonCellTemplate.VisualTree = objRadButtonColumnFactory;
    objRadioButtonColumn.CellTemplate = RadioButtonCellTemplate;

    YourViewModel.CustomColumns.Add(objRadioButtonColumn);

    foreach (DataColumn objColumn in objTable.Columns)
    {
        DataGridTextColumn objDgridColumn = new DataGridTextColumn();
        objDgridColumn.Header = objColumn.ColumnName;

        Binding objBinding = new Binding();
        objBinding.Path = new PropertyPath(objColumn.ColumnName);

        objDgridColumn.Binding = objBinding;

        YourViewModel.CustomColumns.Add(objDgridColumn);
    }
}



现在,我们必须绑定 DataGridColumns的 ObservableCollection / b>到datagrid。在这一点上,我无法将此集合绑定到DataGrid的Columns属性。为此我从下面的StackOverflow链接中引用了解决方案,



c# - 如何将WPF DataGrid绑定到可变数量的列? - 堆栈溢出 [ ^ ]



根据这个StackOverflow解决方案,我刚刚添加了 DataGridColumnsBehavior 我的解决方案中的课程。并更改了DataGrid xaml,如下所示,


Now, we have to bind this ObservableCollection of DataGridColumns to the datagrid. In this point, I cannot bind this collection to DataGrid's Columns property. For that I have referred the solution from StackOverflow link below,

c# - How do I bind a WPF DataGrid to a variable number of columns? - Stack Overflow[^]

According to this StackOverflow solution, I just added DataGridColumnsBehavior class in my solution. And changed DataGrid xaml like below,

<DataGrid x:Name="MyDataGrid" HorizontalAlignment="Left" VerticalAlignment="Top"  ItemsSource="{Binding myTable}" AutoGenerateColumns="False" local:DataGridColumnsBehavior.BindableColumns="{Binding CustomColumns}" />



使用此功能。


Use this.


这篇关于将数据表绑定到MVVM WPF中的datagrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆