我试图在代码隐藏中创建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#?