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 #?
source share