2011-06-09 17 views
4

我試圖在代碼隱藏中創建DataTemplate。我有一個DataTrigger在它的問題。在代碼中創建DataTemplate和DataTrigger

這裏的DataTemplate寫在XAML:

<DataTemplate x:Key="XamlTemplate" > 
    <TextBox Text="{Binding Name}" Name="element" Width="100"/> 
    <DataTemplate.Triggers> 
     <DataTrigger Binding="{Binding Flag}" Value="true"> 
      <DataTrigger.EnterActions> 
       <BeginStoryboard> 
        <Storyboard> 
         <DoubleAnimation Storyboard.TargetName="element" Storyboard.TargetProperty="Width" 
              To="200" Duration="0:0:2" /> 
        </Storyboard> 
       </BeginStoryboard> 
      </DataTrigger.EnterActions> 
     </DataTrigger> 
    </DataTemplate.Triggers> 
</DataTemplate> 

這裏就是我寫在C#

var template = new DataTemplate(); 

//create visual tree 
var textFactory = new FrameworkElementFactory(typeof(TextBox)); 
textFactory.SetBinding(TextBox.TextProperty, new Binding("Name")); 
textFactory.SetValue(TextBox.NameProperty, "element"); 
textFactory.SetValue(TextBox.WidthProperty, 100D); 
template.VisualTree = textFactory; 

//create trigger 
var animation = new DoubleAnimation(); 
animation.To = 200; 
animation.Duration = TimeSpan.FromSeconds(2); 
Storyboard.SetTargetProperty(animation, new PropertyPath("Width")); 
Storyboard.SetTargetName(animation, "element"); 

var storyboard = new Storyboard(); 
storyboard.Children.Add(animation); 

var action = new BeginStoryboard(); 
action.Storyboard = storyboard; 

var trigger = new DataTrigger(); 
trigger.Binding = new Binding("Flag"); 
trigger.Value = true; 
trigger.EnterActions.Add(action); 

template.Triggers.Add(trigger); 

一組該數據模板作爲按鈕的ContentTemplate。按鈕是綁定到簡單類的數據,這不是問題。

問題是,當我使用在代碼中創建的數據模板,然後當Flag屬性更改我得到以下異常 'element' name cannot be found in the name scope of 'System.Windows.DataTemplate'。雖然用xaml編寫的模板完美地工作。

那麼我在哪裏失敗翻譯XAML到C#?

回答

7

元素的Name有點特殊情況(例如請參閱備註here)。

你要刪除的行

textFactory.SetValue(TextBox.NameProperty, "element"); 

,並設置FrameworkElementFactory.Name代替:

textFactory.Name = "element"; 

這是因爲如果該屬性創建之後設置(這是你做了什麼),它是沒有以相同的方式註冊更長時間。

從代碼中設置名稱很重要的一個值得注意的情況是,在爲故事板運行的元素註冊名稱時,可以在運行時引用它們。在註冊名稱之前,可能還需要實例化並分配一個NameScope實例。請參閱示例部分或Storyboards Overview