2011-04-03 23 views
0

我正在學習如何製作一個Visual Studio風格的屬性網格。我有一個2列GridView,當前綁定確定一個包含兩個字符串成員的對象列表。目前很好。我希望第二列使用文本輸入框,以便我可以更新這些值。 我已經查看了擴展在線,但只能找到這個XAML的例子。我得到了什麼至今(不工作,只顯示不可編輯的文本)...新手使用C#中的GridView CellTemplate#

 GridView gv = new GridView(); 
     View = gv; 

     // First Collumn - Name. 
     GridViewColumn col = new GridViewColumn(); 
     col.Header = "Property"; 
     col.Width = 100; 
     col.DisplayMemberBinding = new Binding("Name"); 
     gv.Columns.Add(col); 

     // 2nd Column - Value. 
     col = new GridViewColumn(); 
     col.Header = "Value"; 
     col.Width = 100; 
     col.DisplayMemberBinding = new Binding("DefaultValue"); 

     FrameworkElementFactory txt = new FrameworkElementFactory(typeof(TextBox)); 
     txt.SetBinding(TextBox.TextProperty, new Binding()); // sets binding 

     // add textbox template 
     col.CellTemplate = new DataTemplate(typeof(string)); 
     col.CellTemplate.VisualTree = txt; 

     gv.Columns.Add(col); 
+1

Yuck,這麼多代碼背後,你爲什麼要這樣做?使用XAML有什麼問題? – 2011-04-03 02:59:53

+0

它可能以XAML結尾,但我很固執,並且想要學習如何在代碼隱藏中做到這一點。我正在重新面對一個C++ MFC應用程序,所以在某些情況下強制使用代碼比我在'純粹'WPF設計中使用代碼更多。 – Jeff 2011-04-03 03:49:31

+0

XAML標記非常有用,它可以爲您節省大量工作,並且它更短,更不易出錯。特別是當涉及到模板後面的代碼是一個*真正*痛苦的時候,因爲在XAML中你必須使用'FrameworkElementFactories',它與聲明一個正常控件沒有什麼不同。 – 2011-04-03 03:53:16

回答

2

+1上使用XAML爲這個意見,但是,這並不回答你的問題。

我懷疑文本框是隻讀的原因是因爲你直接綁定到字符串。如果WPF讓你編輯它,它會在哪裏存儲字符串?如你所知,.NET中的字符串是不可變的。

試試這個:

class StringContainer 
{ 
    public string SomeValue { get; set; } 
} 

現在連線起來是這樣的:

FrameworkElementFactory txt = new FrameworkElementFactory(typeof(TextBox)); 
txt.SetBinding(TextBox.TextProperty, new Binding("SomeValue")); // sets binding 

// add textbox template 
col.CellTemplate = new DataTemplate(typeof(StringContainer)); 

當您綁定的數據,記得包裹編輯字符串StringContainer對象。

myDataRow.DefaultValue = new StringContainer("Some string"); 
+1

太棒了!按需要工作。自我注意:使用CellTemplate時,不要使用DisplayMemberBinding(似乎覆蓋/取消CellTemplate)。 – Jeff 2011-04-03 06:49:40