我試圖在代碼隱藏中創建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#?