简体   繁体   English

绑定清单 <object> 到Datagrid WPF,C#

[英]Bind List<object> to Datagrid WPF, C#

I'm totally new to WPF so heres my code: 我对WPF完全陌生,所以这里是我的代码:

 <DataGrid x:Name="dgVarConfig" ItemsSource="{Binding varConfigList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="10,59,0,0" VerticalAlignment="Top" Height="403" Width="1278" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" HeadersVisibility="Column">

            <DataGrid.Columns>
                <DataGridTextColumn  Width="auto" Header="Match Ausdruck" Binding="{Binding match_expression}"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

My Files: MainWindow.xaml, MainController.cs, VarConfigDAO.cs 我的文件:MainWindow.xaml,MainController.cs,VarConfigDAO.cs

the varConfigDAO.cs returns the list to the MainController, and the MainController.cs returns it do MainWindows.xaml. varConfigDAO.cs将列表返回给MainController,MainController.cs将其返回给MainWindows.xaml。

This is the VarConfig.cs: 这是VarConfig.cs:

 public class VarConfig
    {
        public int id { get; set; }
        public String group { get; set; }
        public String machine { get; set; }
        public String match_expression { get; set; }
        public String variant_new_1 { get; set; }
        public String calc_formula_1 { get; set; }
        public String variant_new_2 { get; set; }
        public String calc_formula_2 { get; set; }
    }

It works if i set the itemssource programmaticly: 如果我以编程方式设置itemssource,它将起作用:

dgVarConfig.Itemssource = mainController.loadVarConfigList();

But thats not what i want because i want to update the list via the grid (insert, delete, update lines => Mode=TwoWay) 但这不是我想要的,因为我想通过网格更新列表(插入,删除,更新行=> Mode = TwoWay)

Any clue how i can fill the itemssource via xaml? 任何线索,我怎么能通过XAML填充itemsource?

Create a view model class with a property that holds a collection of VarConfig objects. 创建一个具有包含VarConfig对象集合的属性的视图模型类。 The collection should notify the view about changes (like added or removed elements). 集合应该通知视图有关更改(例如添加或删除的元素)。 An appropriate collection type would therefore be ObservableCollection: 因此,合适的集合类型将是ObservableCollection:

public class ViewModel
{
    public ViewModel()
    {
        VarConfigList = new ObservableCollection<VarConfig>();
    }

    public ObservableCollection<VarConfig> VarConfigList { get; private set; }
}

Set the DataContext of your UI (eg your MainWindow) to an instance of the view model, for example in code behind in the MainWindow constructor like this: 将UI(例如,MainWindow)的DataContext设置为视图模型的实例,例如在MainWindow构造函数后面的代码中,如下所示:

public MainWindow()
{
    InitializeComponent();

    var viewModel = new ViewModel();
    // fill viewModel.VarConfigList

    DataContext = viewModel;
}

Bind to the VarConfigList property in XAML. 绑定到XAML中的VarConfigList属性。 It is not necessary to set Mode=TwoWay or UpdateSourceTrigger=PropertyChanged , as the ItemsSource property is only bound one-way (the DataGrid - or any other ItemsControl - never sets it): 不必设置Mode=TwoWayUpdateSourceTrigger=PropertyChanged ,因为ItemsSource属性仅是单向绑定的(DataGrid-或任何其他ItemsControl-从未设置):

<DataGrid ItemsSource="{Binding VarConfigList}" ...>
    ...
</DataGrid>

Finally, if you also want the UI to react on changes of the individual VarConfig properties, it should implement the INotifyPropertyChanged interface: 最后,如果您还希望UI对单个VarConfig属性的更改做出反应,则应实现INotifyPropertyChanged接口:

public class VarConfig : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private int id;
    public int Id
    {
        get { return id; }
        set
        {
            id = value;
            OnPropertyChanged("Id");
        }
    }

    // similar code for the other properties
}

Note the casing. 注意外壳。 It's widely accepted to write C# property names in PascalCase . PascalCase编写C#属性名已被广泛接受。

You are going to have to set the DataContext for your DataGrid to whatever object has varConfigList in it. 您将必须将DataGridDataContext设置为其中包含varConfigList任何对象。 Then, the DataGrid will be able to see varConfigList and do it's stuff. 然后, DataGrid将能够看到varConfigList并完成它的工作。 You don't give a lot of code, so it I can't see what you are after, but I'm going to make some guesses, and see if they help. 您不会提供很多代码,所以我看不到您想要什么,但是我将做出一些猜测,看看它们是否有帮助。

There are a few ways to do it. 有几种方法可以做到这一点。 I take it the DataGrid is in your MainWindow , so it will normally inherit its DataContext from there; 我认为DataGrid在您的MainWindow ,因此它将通常从那里继承其DataContext but you can also set it individually. 但您也可以单独设置。

Here is one possible way: 这是一种可能的方法:

MainWindow 主窗口

<Window ...>
    <DataGrid ... ItemsSource={Binding VarConfigList} ... />
</Window>

public partial class MainWindow : Window
{
  ...
  MainWindow()
  {
       InitializeComponent();
       this.DataContext = new MainController();
  }
}

MainController 主控制器

class MainControler 
{
    private var _varConfigList;
    public var VarConfgList { get { return _varConfigList; } }
    ...

    public MainControler()
    { 
       // set stuff up 
    }
}

Then your next problem is how to get the DataGrid to treat VarConfigList as you want, but that is another story. 然后,您的下一个问题是如何使DataGrid VarConfigList地对待VarConfigList ,但这是另一回事了。

In my limited experience, sorting out the DataContexts has been the biggest obstacle in learning WPF. 以我有限的经验,整理DataContexts是学习WPF的最大障碍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM