gpt4 book ai didi

wpf - 在代码中创建DataTemplate和DataTrigger

转载 作者:行者123 更新时间:2023-12-02 00:09:17 25 4
gpt4 key购买 nike

我正在尝试创建 DataTemplate在代码隐藏中。我对DataTrigger有疑问就在其中。

这是用 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);

A将此数据模板设置为ContentTemplate一个按钮的。按钮是将数据绑定(bind)到简单的类,这不是问题。

问题是,当我使用在代码中创建的数据模板时,当 Flag 属性更改时,我收到以下异常在“System.Windows.DataTemplate”的名称范围中找不到“element”名称。而用 xaml 编写的模板可以完美运行。

那么我在哪里将 xaml 翻译成 c# 失败了?

最佳答案

元素的名称有点特殊(例如,请参阅备注 here)。

您想挂断电话

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

并设置FrameworkElementFactory.Name:

textFactory.Name = "element";

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

One notable case where setting Name from code is important is when registering names for elements that storyboards will run against, so that they can be referenced at run time. Before you can register a name, might also need to instantiate and assign a NameScope instance. See the Example section, or Storyboards Overview.

关于wpf - 在代码中创建DataTemplate和DataTrigger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6295727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com