5

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.

1
  • Yes it is possible but... Show us some code! Your class, your DataGrid, and your objective: what exactly do you want to bind?
    – Damascus
    Sep 17, 2012 at 14:12

1 Answer 1

18

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!

2
  • I have extended the example so you can see more clearly that it does use a class. However, are you suggesting that you still want to auto generate the columns and simply exclude some of them?
    – AlSki
    Sep 17, 2012 at 14:25
  • thanks! that was pretty much what i was looking for. however if there's a way to do it without setting auto generate columns, i'd really like to know.
    – Amber
    Sep 17, 2012 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.