How to create this DataTemplate in code behind

Mar 8, 2010 at 2:56 PM


I came across with an issue, I have the next DataTemplate in my Xaml  

<DataTemplate x:Key="dttest">
            <w:ScoreControl Items="{Binding Path=ScoreVariables[0].PossibleScores}" SelectedValue="{Binding Path=ScoreVariables[0].InherentSelectedValue}"   />


That DataTemplate is working fine when I use as CellTemplate in my DataGrid. The thing is that I need to create several of that DataTemplate in code. By the way the ScoreControl is a customized control that I'm using that has Items and every item has a name and value. What I have so far is:


void GenerateTemplate(int index, bool IsInherent)
            Binding itemsBinding = new Binding();
            itemsBinding.Path = new PropertyPath(string.Format("ScoreVariables[{0}]", index));
            itemsBinding.Mode = BindingMode.OneWay;

            Binding selectedBinding = new Binding();
            if (IsInherent)
                selectedBinding.Path = new PropertyPath(string.Format("ScoreVariables[{0}].InherentSelectedValue", index));
                selectedBinding.Path = new PropertyPath(string.Format("ScoreVariables[{0}].ResidualSelectedValue", index));

            selectedBinding.Mode = BindingMode.OneWay;
            FrameworkElementFactory scoreFactory = new FrameworkElementFactory(typeof(ComboBox));
            scoreFactory.Name = "score";
            scoreFactory.SetBinding(ScoreControl.SelectedValueProperty, selectedBinding);
            scoreFactory.SetBinding(ScoreControl.ItemsProperty, itemsBinding);
            DataTemplate dtTest = new DataTemplate();
            dtTest.VisualTree = scoreFactory;
            this.Resources.Add(string.Format(IsInherent?"I-{0}":"R-{0}", index),dtTest);
That is not working well, only work the ItemsProperty, the SelectedValue is not binded. 
Seems that it works only with one property to bind, I tried to use only the selectedValue property and it works.
Pleas help me, I'have used two binding properties before I'dont know why is not working with that.