在代码中创建DataTemplate和DataTrigger

4
我想在代码后台创建数据模板,但是其中的数据触发器存在问题。
以下是在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#时出了什么问题?
1个回答

6

元素的Name有点特殊(例如,有关说明请参见此处)。

您想要删除这行。

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

而设置FrameworkElementFactory.Name代替:

textFactory.Name = "element";

这是因为如果属性在创建后设置(就像你所做的那样),它不再以同样的方式注册。
一个值得注意的情况是,当为故事板运行的元素注册名称时,从代码中设置名称非常重要,以便在运行时可以引用它们。在注册名称之前,您可能还需要实例化和分配NameScope实例。请参见示例部分或Storyboards Overview

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接