Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to bind a datagrid to only selective members 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.

like image 216
Amber Avatar asked Sep 17 '12 14:09

Amber


1 Answers

Yes, Just turn off the AutoGenerateColumns and manually specify them

In 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

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

In 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!

like image 63
AlSki Avatar answered Oct 14 '22 02:10

AlSki