I have in xaml as following:
<StackPanel Orientation="Horizontal" Margin="0 5 0 0" HorizontalAlignment="Center" VerticalAlignment="Bottom">
<TextBox Text="LinkColor" VerticalAlignment="Center" IsReadOnly="True"/>
<ComboBox x:Name="ColorCombo" MinWidth="180" Margin="5 0 0 0" SelectionChanged="ColorCombo_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding Key}" VerticalAlignment="Center" Height="10" Width="20"/>
<TextBlock Text="{Binding Key}" Margin="5 0 0 0" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
This will create a label on the right side and a combo box on the right side.
The Itemssource for combo box will come from the code as:
ColorCombo.ItemsSource = ColorsDictionary;
Here colorsdictionary is defined as:
Dictionary<string, Color> ColorsDictionary = new Dictionary<string, Color>();
But now, i am trying to add combo and the entire Itemtemplate through code. But I am not getting how to do( bind the data) through code, anyone can help me out?
To answer you question you can create a
Bindingprogramatically like this:-However that isn’t actually that useful to you.
The
DataTemplatecannot be created in code in the manner above. The only way to build aDataTemplateprogrammatically is to create a Xaml string (perhaps with the aid ofXDocument) and then useXamlReaderto load the generated Xaml. Are you really sure you need to do all this programmatically?