我想在代码后台创建数据模板,但是其中的数据触发器存在问题。
以下是在xaml中编写的DataTemplate:
将此数据模板设置为按钮的ContentTemplate。 按钮绑定到简单类,这不是问题。
问题在于当我使用在代码中创建的数据模板时,当
那么我在将xaml翻译成C#时出了什么问题?
以下是在xaml中编写的DataTemplate:
<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#时出了什么问题?