在代码中创建DataTemplate和DataTrigger

alp*_*use 4 wpf datatrigger code-behind datatemplate

我正在尝试在代码隐藏中创建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>
Run Code Online (Sandbox Code Playgroud)

这是我用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);
Run Code Online (Sandbox Code Playgroud)

将此数据模板设置为按钮的ContentTemplate.Button是绑定到简单类的数据,这不是问题.

问题是,当我使用在代码中创建的数据模板时,当Flag属性更改时,我得到以下异常 'element' name cannot be found in the name scope of 'System.Windows.DataTemplate'.虽然用xaml编写的模板工作得很好.

那么我在哪里无法将xaml转换为c#?

H.B*_*.B. 6

Name元素是一个有点特殊的情况(见备注这里的例子).

你想放弃这条线

textFactory.SetValue(TextBox.NameProperty, "element");
Run Code Online (Sandbox Code Playgroud)

并设置FrameworkElementFactory.Name相反:

textFactory.Name = "element";
Run Code Online (Sandbox Code Playgroud)

这是因为如果在创建后设置属性(这就是你所做的),它就不再以相同的方式注册.

从代码中设置Name很重要的一个值得注意的情况是,为故事板运行的元素注册名称时,可以在运行时引用它们.在注册名称之前,可能还需要实例化并分配NameScope实例.请参阅示例部分或故事板概述.