如何将 datagrid 绑定到 wpf 中某个类的某些属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12460987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:23:18  来源:igfitidea点击:

How can i bind datagrid to some properties of a class in wpf?

wpfclassdata-bindingdatagrid

提问by Amber

Is it possible to bind a datagrid to only selectivemembers of a class? The way I have made the binding presently, all the class variables have been binded(one to one mapped) to datagrid's columns.

是否可以将数据网格仅绑定到类的选择性成员?我目前进行绑定的方式是,所有类变量都已绑定(一对一映射)到数据网格的列。

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

Now i want only a few class properties(not all) to be binded to the datagrid.

现在我只想将几个类属性(不是全部)绑定到数据网格。

回答by AlSki

Yes, Just turn off the AutoGenerateColumns and manually specify them

是的,只需关闭 AutoGenerateColumns 并手动指定它们

In MainWindow.xaml

在 MainWindow.xaml 中

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Hello}" Header="Hello" />
        <DataGridTextColumn Binding="{Binding World}" Header="World" />
    </DataGrid.Columns>
</DataGrid>

In MainWindow.xaml.cs

在 MainWindow.xaml.cs 中

  public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new[] { new FakeViewModel() };
    }
}

In FakeViewModel.cs

在 FakeViewModel.cs 中

namespace WpfApplication4
{
  class FakeViewModel
  {
    public FakeViewModel()
    {
        Hello = "Hello";
        World = "World";
        Then = DateTime.Now;
    }
    public DateTime Then { get; set; }
    public string Hello { get; set; }
    public string World { get; set; }
  }
}

Please note the unused Property Then!

请注意未使用的属性那么!