2014-05-14 86 views
1

我想知道如何將一個DataGrid DataGridTemplateColumn綁定到一個屬性,該屬性不在DataGrid的ItemSource中,但該屬性在Itemsource的同一個DataContext中?WPF綁定到一個屬性不在DataGrid中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; } 
    } 

才能實現這一目標?

感謝

+0

儘管你告訴我們,一個屬性'CustomerCollection '在視圖模型類中,您將ItemsSource綁定到駐留在ResourceDictionary中的集合中,並使用鍵「CustomerCollection」。這沒有什麼意義。 – Clemens

+1

對不起 - 我解釋說,集合來自CollectionViewSource,因爲我需要在CustomerCollection上進行過濾。 – user3428422

+0

好的。假設DataGrid的DataContext是ViewModel類的一個實例,您應該能夠通過'Visibility =「{Binding Visible}」或'Visibility =「{Binding Path = Visible}」'綁定可見性。 – Clemens

回答

4

DataGrid列不來了DataGrid的視覺樹下。因此您將需要使用BindingProxy使ViewModel可以訪問您的DataGridTemplateColumn。我已經解釋瞭如何創建並在以下答案中使用BindingProxy

Bind ViewModel property to DataGridComboBoxColum

一旦你已經設置了BindingProxy您可以DataGridTemplateColumn可視性綁定爲

<DataGridTemplateColumn Header="Apply" Visibility="{Binding Path=Data.Visible, Source={StaticResource ProxyElement}" 
+0

他們爲什麼要(微軟)必須這樣設計它?但工程師,謝謝 – user3428422

相關問題