Creating a DataTemplate and DataTrigger in Code

I am trying to create a DataTemplate in code. And I have a problem with DataTrigger .

Here is the DataTemplate, as written in 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> 

and here is what I wrote in 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); 

Set this data template as the ContentTemplate button. Button is data tied to a simple class, which is not a problem.

The problem is that when I use the data template created in the code, then when I change the Flag property, I get the following exception 'element' name cannot be found in the name scope of 'System.Windows.DataTemplate' . Although the template written in xaml works fine.

So where have I not translated xaml to C #?

+4
source share
1 answer

Name elements are a small special case (see notes here ).

Do you want to delete row

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

And set instead of FrameworkElementFactory.Name :

 textFactory.Name = "element"; 

This is because if a property is set after creation (this is what you did), it is no longer registered in the same way.

One of the notable cases when the value of the "Name from Code" parameter is important is to register the names of the elements with which the storyboards will be executed so that they can be referenced at run time. Before you can register a name, you may also need to create an instance of NameScope . See the Example Section or Storyboard Overview .

+7
source

All Articles