2012-09-30 70 views
2

我有以下DataTemplate綁定的DataTemplate內容

<DataTemplate x:Key="ButtonTemplate"> 
    <Button Click="Cell_Click"> 
     <Button.Template> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <TextBlock x:Name="TBlock" /> 
      </ControlTemplate> 
     </Button.Template> 
    </Button> 
</DataTemplate> 

而且我用這個DataTemplateGridViewColumn.CellTemplate,但我必須動態綁定TextBlockText屬性,當我添加一個新的列:

GridViewColumn column = new GridViewColumn(); 
column.CellTemplate = Resources["ButtonTemplate"] as DataTemplate; 
// How to get the TBlock (TextBlock) of CellTemplate and bind its property here? 
MyGridView.Columns.Add(column); 

我該怎麼辦?謝謝。

回答

0

忘記修改模板,您最好從頭開始在代碼中創建它(或者您可以使用XamlReader.Parse和帶有動態插入綁定代碼的XAML字符串)。

+0

什麼是我必須解析的字符串? – Nick

+0

@Nick:在XAML中包含您的數據模板的字符串,在SO上搜索方法名稱,您將找到示例。 –

0

您可以爲TextBlock的Loaded-Event附加一個EventHandler,並在其中創建綁定(基於TextBlock的DataContext,如果這是足夠的信息)。

+0

不,我不能。我沒有足夠的信息。 – Nick

+0

問題是您的模板在創建列時沒有實例化,因此您無法使用FindName。你必須等到它被加載。那麼你應該可以這樣做:http://marcozhou.wordpress.com/2008/01/03/how-to-reference-named-elements-within-celltemplate/ –

+0

我必須綁定Text屬性到名爲'(「Box」+ MyGridView.Coulmns.Count)'的屬性。你能舉個例子嗎?在XAML中,如果我寫了'Text = {Binding Box1}'它有效,但我必須動態地選擇正確的名稱。 – Nick