Wpf datagrid双向绑定:在按钮上单击添加行 [英] Wpf datagrid two way binding: add row on button click

查看:78
本文介绍了Wpf datagrid双向绑定:在按钮上单击添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的新手。我挣扎了一个星期在按钮点击的数据网格中添加一行。



我的数据网格绑定到

I am new to WPF. I am struggling for a week to add a row in datagrid on a button click.

My datagrid is bound to

ObservableCollection<FilterCriteria> FilterCriteriaList





很抱歉添加这样的长度代码。作为WPF的新手,我不确定我到底缺少什么。所以尽量提供尽可能多的信息



这是我的FilterCriteria课程





Sorry for adding such a length code. Being new to WPF, I am not sure what exactly I am missing here. So trying to provide as much information as possible

This is my FilterCriteria class

public class FilterCriteria : INotifyPropertyChanged
    {
        private NORTHWNDEntities context = new NORTHWNDEntities();

        private string columnName;
        public string ColumnName
        {
            get
            {
                return columnName;
            }
            set
            {
                columnName = value;
                RaisePropertyChanged("ColumnName");
            }
        }

        private string _operator;
        public string Operator
        {
            get
            {
                return _operator;
            }
            set
            {
                _operator = value;
                RaisePropertyChanged("Operator");
            }
        }

        private string inputValue;
        public string InputValue
        {
            get
            {
                return inputValue;
            }
            set
            {
                inputValue = value;
                RaisePropertyChanged("InputValue");
            }
        }

        private string selectedTable;
        public string SelectedTable
        {
            get
            {
                return selectedTable;
            }
            set
            {
                selectedTable = value;
                RaisePropertyChanged("SelectedTable");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged([CallerMemberName]string propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }





这是我的ViewModel代码





This is my ViewModel Code

public class ExportTablesViewModel : INotifyPropertyChanged
    {
        private NORTHWNDEntities context = new NORTHWNDEntities();

        private ObservableCollection<DatabaseTable> tableNameList;
        public ObservableCollection<DatabaseTable> TableNameList
        {
            get
            {
                return tableNameList;
            }
            set
            {
                tableNameList = value;
                RaisePropertyChanged("TableNameList");
            }
        }

        private ObservableCollection<string> selectedTableColumnList;

        public ObservableCollection<string> SelectedTableColumnList
        {
            get
            {
                return selectedTableColumnList;
            }
            set
            {
                selectedTableColumnList = value;
                RaisePropertyChanged("SelectedTableColumnList");
            }
        }


        private ObservableCollection<FilterCriteria> filterCriteriaList;

        public ObservableCollection<FilterCriteria> FilterCriteriaList
        {
            get
            {
                return filterCriteriaList;
            }
            set
            {
                filterCriteriaList = value;
                RaisePropertyChanged("FilterCriteriaList");
            }
        }


        private string selectedTableName;

        public string SelectedTableName
        {
            get
            {
                return selectedTableName;
            }
            set
            {
                selectedTableName = value;
                RaisePropertyChanged("SelectedTableName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged([CallerMemberName]string propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }





这是网格的xaml代码:





This is xaml code for the grid:

<DataGrid x:Name="dataGridFilters" CanUserAddRows="True"  ItemsSource="{Binding FilterCriteriaList}" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="313,31,0,0" VerticalAlignment="Top" Height="261" Width="679">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Column">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox x:Name="ComboBoxColumnName" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedTableColumnList}" 
                                      SelectedValue="{Binding Path=ColumnName,Mode =TwoWay,UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True,NotifyOnSourceUpdated=True}" SelectedValuePath="ColumnName"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Operator">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="TextBoxOperator" Text="{Binding Path=Operator,Mode =TwoWay,UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True,NotifyOnSourceUpdated=True}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Value">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="TextBoxInputValue" Text="{Binding Path=InputValue,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True,NotifyOnSourceUpdated=True}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button x:Name="buttonAddFilter" Content="+" HorizontalAlignment="Left" Margin="958,76,0,0" VerticalAlignment="Top" Width="34" RenderTransformOrigin="0.5,0.5" Click="buttonAddFilter_Click">
        </Button>





点击按钮,我试图在网格中添加行。为此,我添加了viewModel.FilterCriteriaList.Add(new FilterCriteria());在buttonAddFilter_Click事件中。此代码在datagrid中添加为新行。但是当我在新添加的行中输入一些值时。它没有被添加到FilterCriteriaList集合中



请告诉我,如何对新添加的行进行双向绑定?



我尝试了什么:



已经解释过,就像我定义的视图模型一样,ObservableCollection ,xaml代码



On click on the button, I am trying to add the row in the grid. To do that, I'm adding viewModel.FilterCriteriaList.Add(new FilterCriteria()); in buttonAddFilter_Click event. This code add as new row in the datagrid. But when I enter some value in newly added row. It doesn't get added to the FilterCriteriaList collection

Kindly let me know, how to do two way binding for newly added row?

What I have tried:

already explained in question, like how I have defined view model, ObservableCollection, xaml code

推荐答案

首先,您不需要使用可观察集合来更改属性,内置它。其次,您应该避免使用new绑定到可观察集合时的关键字,因为它会破坏绑定。可观察集合在clear()和add()事件上引发属性更改因此



1)声明绑定Observable Collection一次
First off you don't need to raise property changed with an observable collection, its built in. Second, you should avoid using the "new" key word when binding to an observable collection because that breaks the binding. Observable collections raise property changed on clear() and add() events so

1) Declare you bound Observable Collection once
public ObservableCollection<FilterCriteria> FilterCriteriaList { get; set; }





然后在你的构造函数中你可以实例化。



Then in your constructor you can instantiate.

public ExportFiltersViewModel() 
{ 
   FilterCriteriaList = new ObservableCollection<FilterCriteriaList>(); 
};





接下来在你的视图中你没有显示双向



Next in your view you are not showing two-way

<DataGrid x:Name="dataGridFilters" CanUserAddRows="True"  ItemsSource="{Binding FilterCriteriaList, Mode="Two-Way" }"





现在,您应该在此处查找ICommand属性以将Button click事件绑定到视图模型,这样它应该看起来像



Now here is where you should look up the ICommand properties to bind the Button click event to your view model so it should look something like

<Button x:Name="buttonAddFilter" Content="+" HorizontalAlignment="Left" Margin="958,76,0,0" VerticalAlignment="Top" Width="34" RenderTransformOrigin="0.5,0.5" Command="{Binding ButtonClickCommand}">





或者如果您在xaml.cs中引用了您的viewmodel,那么在事件上抓住您的viewmodel并做这样的事情



or if you have your viewmodel referenced in your xaml.cs then on the event just grab your viewmodel and do something like this

FilterCriteria criteria = new FilterCriteria()
{ //populate properties here or however you populate your object
};

vm.FilterCriteriaList.Add(criteria); //This add triggers the INotify in ObservableCollection





你的行应该添加。



Your row should add.


这篇关于Wpf datagrid双向绑定:在按钮上单击添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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