2

I am wondering how I can bind a DataGrid DataGridTemplateColumn to a property in that isn't in the DataGrid ItemSource, but the property is within the same DataContext of the Itemsource?

XAML

        // I am trying to bind the Visibility property to a property called Visible
        <DataGridTemplateColumn Header="Apply" Visibility="{Binding source Visible}">

        // However the visible property doesnt exist inside the resource cvsCustomers
        ItemsSource="{Binding Source={StaticResource CustomerCollection}}"

C#

    // But they both live in the same ViewModel i.e. DataContext      
    private Visibility m_Visible = Visibility.Hidden;

    public Visibility Visible
    {
       get { return m_Visible; }
       set { m_Visible = value; }
    }

    private ObservableCollection<Customer> m_CustomerCollection = null;

    public ObservableCollection<Customer> CustomerCollection
    {
       get { return m_CustomerCollection; }
       set { m_CustomerCollection = value; }
    }

Can this be achieved?

Thanks

user3428422
  • 4,300
  • 12
  • 55
  • 119
  • Although you show us a property `CustomerCollection` in your view model class, you are binding the ItemsSource to a collection that resides in a ResourceDictionary, with key "CustomerCollection". That doesn't make much sense. – Clemens May 14 '14 at 09:11
  • 1
    Sorry - I explain, the collection is from a CollectionViewSource as I need to filter on the CustomerCollection. – user3428422 May 14 '14 at 09:25
  • Ok. Provided that the DataContext of the DataGrid is an instance of your ViewModel class, you should be able to bind the Visibility by `Visibility="{Binding Visible}"` or `Visibility="{Binding Path=Visible}"`. – Clemens May 14 '14 at 09:45

1 Answers1

4

Datagrid columns does not comes under the visual tree of the DataGrid. hence you will need to use the BindingProxy to make ViewModel accessible to your DataGridTemplateColumn. I have explained how to create and use BindingProxy in the answer below:

Bind ViewModel property to DataGridComboBoxColum

Once you have setup the BindingProxy you can bind your DataGridTemplateColumn visiblity as

<DataGridTemplateColumn Header="Apply" Visibility="{Binding Path=Data.Visible, Source={StaticResource ProxyElement}" 
Community
  • 1
  • 1
Nitin
  • 18,344
  • 2
  • 36
  • 53