How to create a DataTrigger programatically with Binding="{Binding}"? - c#

What's the equivelant of this DataTrigger in C# code?
<DataTrigger
Binding="{Binding}"
Value="{x:Null}">
<Setter
Property=SomeProperty
Value=SomeValue />
</DataTrigger>
I am skeptical on how to create the Binding. Is this correct?
var trigger = new DataTrigger();
trigger.Value = null;
// Is this sufficient?
trigger.Binding = new Binding();
// Code to create the setter
// ...

This would be the equivalent of your XAML:
var trigger = new DataTrigger()
{
Value = null,
Binding = new Binding(".")
};
trigger.Setters.Add(new Setter() { Property = SomeProperty, Value = SomeValue });

Related

Set CornerRadius of CheckBox in code behind

I have an application that allows multiple selection of items in the UI with checkboxes. The thing is checkboxes are generated from a file because the company adds or removes selections from the search.
Since I read a file to get all the possible selections available, the checkbox is generated in C# code, not XAML and one requirement for the UI is to have rounded checkboxes. How can I achieve this in C#?
I did this in XAML:
<CheckBox Content="QA Standard" IsEnabled="{Binding CanEdit, UpdateSourceTrigger=PropertyChanged}"
ToolTip="{Binding StatusInfo, UpdateSourceTrigger=PropertyChanged}"
BorderBrush="{Binding StatusColor, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="2"
Margin="5" >
<CheckBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="12" />
</Style>
</CheckBox.Resources>
Tried to redo it in C# but doesn't seems to work:
CheckBox c = new CheckBox() { BorderThickness = new Thickness(2), Content = b, Margin = new Thickness(5) };
var enabled = new Binding() { Source = DataContext, Path = new PropertyPath("CanEdit"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var tooltip = new Binding() { Source = DataContext, Path = new PropertyPath("StatusInfo"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var border = new Binding() { Source = DataContext, Path = new PropertyPath("StatusColor"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
BindingOperations.SetBinding( c, CheckBox.IsEnabledProperty, enabled );
BindingOperations.SetBinding( c, CheckBox.ToolTipProperty, tooltip );
BindingOperations.SetBinding( c, CheckBox.BorderBrushProperty, border );
var cStyle = new Style( typeof(Border) );
cStyle.Setters.Add( new Setter( Border.CornerRadiusProperty, new CornerRadius( 12.0 ) ) );
c.Resources.Add( "CornerRadiusBorder", cStyle );
Boxes.Children.Add( c );
Just change the key of the resource:
var cStyle = new Style(typeof(Border));
cStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0)));
c.Resources.Add(typeof(Border), cStyle);

Create DataGridRowsDetails in code behind WPF

i'm working on a new program that will show information about Test on some Tools in my factory.
For doing that i'm creating a DataGrid Control at run time and populate it.This part is working very well.
My problem is to add RowDetails, How can i do that in code behind?
if (datatable.Rows.Count != 0)
{
foreach (DataRow dt in datatable.Rows)
{
if (last_tool_test == "" || last_tool_test != dt[1].ToString())
{
last_tool_test = dt[1].ToString();
txt = new TextBlock();
txt.Text = dt[1].ToString() + " :";
txt.TextDecorations = TextDecorations.Underline;
txt.HorizontalAlignment = HorizontalAlignment.Center;
txt.Margin = new Thickness(0, 0, 0, 7);
data = new DataGrid();
data.Width = double.NaN;
data.Margin = new Thickness(5, 0, 5, 5);
data.HeadersVisibility = DataGridHeadersVisibility.Column;
data.CanUserAddRows = false;
data.CanUserDeleteRows = false;
data.CanUserReorderColumns = false;
data.CanUserResizeColumns = false;
data.CanUserSortColumns = false;
data.IsReadOnly = true;
data.SelectionMode = DataGridSelectionMode.Extended;
DataGridTextColumn col1 = new DataGridTextColumn();
col1.Header = "Recipe Name";
col1.Binding = new Binding("Recipe_Name");
col1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
var style = new Style(typeof(DataGridColumnHeader));
style.Setters.Add(new Setter()
{
Property = HorizontalAlignmentProperty,
Value = HorizontalAlignment.Stretch
});
style.Setters.Add(new Setter()
{
Property = HorizontalContentAlignmentProperty,
Value = HorizontalAlignment.Center
});
style.Setters.Add(new Setter()
{
Property = FontWeightProperty,
Value = FontWeights.Bold
});
var style1 = new Style(typeof(TextBlock));
style1.Setters.Add(new Setter()
{
Property = HorizontalAlignmentProperty,
Value = HorizontalAlignment.Center
});
col1.HeaderStyle = style;
col1.ElementStyle = style1;
data.Columns.Add(col1);
DataGridTextColumn col2 = new DataGridTextColumn();
col2.Header = "Foup";
col2.Width = 100;
col2.Binding = new Binding("Foup");
col2.HeaderStyle = style;
col2.ElementStyle = style1;
data.Columns.Add(col2);
DataGridTextColumn col3 = new DataGridTextColumn();
col3.Header = "Need Reference?";
col3.Width = 110;
col3.HeaderStyle = style;
col3.ElementStyle = style1;
col3.Binding = new Binding("Reference");
data.Columns.Add(col3);
DataGridTextColumn col4 = new DataGridTextColumn();
col4.Header = "# Iteration";
col4.Width = 100;
col4.HeaderStyle = style;
col4.ElementStyle = style1;
col4.Binding = new Binding("Iteration");
data.Columns.Add(col4);
DataGridTextColumn col5 = new DataGridTextColumn();
col5.Header = "Spec";
col5.Width = 100;
col5.HeaderStyle = style;
col5.ElementStyle = style1;
data.Columns.Add(col5);
col5.Binding = new Binding("Spec");
st.Children.Add(txt);
st.Children.Add(data);
}
data.Items.Add(new Tool_Test() { Recipe_Name = dt[2].ToString(), Foup = dt[3].ToString(), Reference = dt[4].ToString(), Iteration = dt[5].ToString(), Spec = dt[6].ToString() });
}
last_tool_test = "";
}
}
edit: I think i found a solution by using resource:
<Window.Resources>
<DataTemplate x:Key="CustomTemplate">
<DataGrid x:Name="datagrid1" HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" SelectionMode="Extended" Margin="5,0,5,50" CanUserResizeColumns="False" AutoGenerateColumns="False" VerticalAlignment="Top" IsReadOnly="True" Width="750">
<DataGrid.Columns>
<DataGridTextColumn Header="Sub Test Name" Width="*" Binding="{Binding Path=Recipe_Name}">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
</DataGridTextColumn.HeaderStyle>
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Spec" Width="*" Binding="{Binding Path=Foup}">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
</DataGridTextColumn.HeaderStyle>
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</Window.Resources>
and in my code i added this:
data.RowDetailsTemplate = (DataTemplate)this.Resources["CustomTemplate"];
Now it's half working. I don't have experience with resource so i can't find a solution to Bind data to it. How can i do that?
Thank you for your help.
You could set the RowDetailsTemplate property to a DataTemplate that you create programmatically using the XamlReader class, e.g.:
string template = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"><TextBlock Text=\"some text...\"></DataTemplate>";
data.RowDetailsTemplate = XamlReader.Parse(template) as DataTemplate;
I have built something along those lines a generic User Control that you can throw any ObservableCollection of objects at it and it will build the table, but you want to define the headers column widths etc. so it doesn't just use the function names for headers and default widths.
First I created an object to hold the settings for each column:
public DataGridColumnSettings(string Header, int ColumnIndex, bool IsReadOnly = true, string Width = "100", bool ComboBoxColumn = false, bool CheckBoxColumn = false)
{
this.Header = Header;
this.ColumnIndex = ColumnIndex;
this.IsReadOnly = IsReadOnly;
this.Width = Width;
this.ComboBoxColumn = ComboBoxColumn;
this.CheckBoxColumn = CheckBoxColumn;
}
I then make a collection of these for each Model (I was using the MVVM pattern):
public static Dictionary<string, DataGridColumnSettings> ColumnSettings
{
get { return new Dictionary<string, DataGridColumnSettings>() { { "PurchaseOrder", new DataGridColumnSettings("Order Number", 0) }, { "Width", new DataGridColumnSettings("Width", 1) }, { "Length", new DataGridColumnSettings("Length", 2) }, { "NumberOfPallets", new DataGridColumnSettings("No of Pallets", 3) }, { "BoardsPerStack", new DataGridColumnSettings("No of Boards", 4) }, { "NumberOfBoards", new DataGridColumnSettings("Total Boards", 5) } }; ; }
}
The dictionary keys are the get set methods from the model for the required value in the table row (this is what the columns will be called by default)
and pass in this dictionary when creating the view object (UserControl) and store it inside the View:
v_DataTable View = new v_DataTable(Model.ColumnSettings);
now add a handler for the data grids Auto Generating Column event:
<DataGrid AutoGeneratingColumn="dataGrid_AutoGeneratingColumn" /> (xaml)
and add the handler to the code behind:
private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
string headername = e.Column.Header.ToString();
//// Any column not in header details is a hidden column
if (this.headerDetails.ContainsKey(headername))
{
Style centerStyle = new Style { TargetType = typeof(DataGridCell) };
centerStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center));
Style headerCenterStyle = new Style { TargetType = typeof(DataGridColumnHeader) };
headerCenterStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
try
{
e.Column.Width = Double.Parse(this.headerDetails[headername].Width);
}
catch(Exception ex)
{
e.Column.Width = 100;
}
// You can also add bindings here if required
Binding headerTextBinding = new Binding();
headerTextBinding.Source = this.headerDetails[headername];
headerTextBinding.Path = new PropertyPath("Header");
headerTextBinding.Mode = BindingMode.TwoWay;
headerTextBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(e.Column, DataGridTextColumn.HeaderProperty, headerTextBinding);
e.Column.HeaderStyle = headerCenterStyle;
e.Column.DisplayIndex = this.headerDetails[headername].ColumnIndex; //// If you have issues with the index been out of range, change the order of the get/set functions in the model class
e.Column.CellStyle = centerStyle; //// putting the get/set for any fields that are not displayed first will also help to avoid the issue
e.Column.IsReadOnly = this.headerDetails[headername].IsReadOnly;
}
else
{
e.Column.Visibility = Visibility.Hidden;
}
}
here you can use the settings you passed in to customise the columns as you require. (Should this be in the View Model if following MVVM pattern?)
I think i found a solution by using resource:
<Window.Resources>
<DataTemplate x:Key="CustomTemplate">
<DataGrid x:Name="datagrid1" HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" SelectionMode="Extended" Margin="5,0,5,50" CanUserResizeColumns="False" AutoGenerateColumns="False" VerticalAlignment="Top" IsReadOnly="True" Width="750">
<DataGrid.Columns>
<DataGridTextColumn Header="Sub Test Name" Width="*" Binding="{Binding Path=Recipe_Name}">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
</DataGridTextColumn.HeaderStyle>
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Spec" Width="*" Binding="{Binding Path=Foup}">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
</DataGridTextColumn.HeaderStyle>
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
and in my code i added this:
data.RowDetailsTemplate = (DataTemplate)this.Resources["CustomTemplate"];
Now it's half working. I don't have experience with resource so i can't find a solution to Bind data to it. How can i do that?

Font size not applied to datagrid columnheader

I have a wpf datagrid in which I am adding all the columns and style through C#.
I have applied ColumnHeaderStyle as follows:
written setter as :
var fontSizeSetter = new Setter {Property = Control.FontSizeProperty, Value = Convert.ToDouble(font.Size)};
Style as:
var headerStyle = new Style();
headerStyle.Setters.Add(fontSetter);
headerStyle.Setters.Add(fontSizeSetter);
headerStyle.Setters.Add(fontStyleSetter);
headerStyle.Setters.Add(fontWeightSetter);
Applied it to my Datagrid's ColumnHeaderStyle as:
view.DataGrid.ColumnHeaderStyle = headerStyle;
Current problem:
now, when I set FontFamily & FontStyle it gets applied. but column Header textsize remains same. It does not get updated.
Entire Method:
private static void ConfigureFontsForDataGrid(Views.StatusMonitor view, StatusMonitorAgencyFontType font)
{
var fontfamily = new FontFamily(font.Font);
var fontSetter = new Setter { Property = Control.FontFamilyProperty, Value = fontfamily };
var fontSizeSetter = new Setter { Property = Control.FontSizeProperty, Value = Convert.ToDouble(font.Size) };
var fontStyleSetter = new Setter { Property = Control.FontStyleProperty };
var fontWeightSetter = new Setter { Property = Control.FontWeightProperty };
// Defaults
fontWeightSetter.Value = FontWeights.Regular;
fontStyleSetter.Value = FontStyles.Normal;
switch (font.Style)
{
case "Regular":
fontWeightSetter.Value = FontWeights.Regular;
fontStyleSetter.Value = FontStyles.Normal;
break;
case "Bold Italic":
fontWeightSetter.Value = FontWeights.Bold;
fontStyleSetter.Value = FontStyles.Italic;
break;
}
//Configuring data grid cell font
view.DataGrid.CellStyle.Setters.Add(fontSetter);
view.DataGrid.CellStyle.Setters.Add(fontSizeSetter);
view.DataGrid.CellStyle.Setters.Add(fontStyleSetter);
view.DataGrid.CellStyle.Setters.Add(fontWeightSetter);
//Configuring data grid column header font
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontSizeSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontStyleSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontWeightSetter);
}
Use this code to resize font of Column Header in Datagrid:
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="FontSize" Value="10"/>
</Style>
Can you try below code.
var headerStyle = new Style();
Setter fontSetter = new Setter { Property = Control.FontFamilyProperty, Value = new FontFamily("Calibri") };
headerStyle.Setters.Add(fontSetter);
Setter fontSizeSetter = new Setter { Property = Control.FontSizeProperty, Value = Convert.ToDouble(20) };
headerStyle.Setters.Add(fontSizeSetter);
Setter fontStyleSetter = new Setter { Property = Control.FontStyleProperty, Value = FontStyles.Italic };
headerStyle.Setters.Add(fontStyleSetter);
Setter fontWeightSetter = new Setter { Property = Control.FontWeightProperty, Value = FontWeights.Bold };
headerStyle.Setters.Add(fontWeightSetter);
myGrid.ColumnHeaderStyle = headerStyle;
I wrote following data template in my datagrid resources. It works.
<DataTemplate DataType="{x:Type System:String}">
<TextBlock Text="{Binding}">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontFamily}" />
<Setter Property="FontSize" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontSize}" />
<Setter Property="FontStyle" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontStyle}"/>
<Setter Property="FontWeight" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontWeight}"/>
</Style>
</TextBlock.Resources>
</TextBlock>
</DataTemplate>

How Can I Convert Xaml Code To C# (Setter Property in WPF)

I have A problem regarding Converting Xaml to C# , I m using Auto complete Box Tab order is not working Properly On that Means First we move all the control and at last I goes on Auto complete Box i m solving this through the xaml code
<ToolKit:AutoCompleteBox.TextBoxStyle>
<Style TargetType="TextBox">
<Setter Property="TabIndex"
Value="{Binding ElementName=txtFirstName, Path=TabIndex}"/>
</Style>
</ToolKit:AutoCompleteBox.TextBoxStyle>
Now on Another i m using All Control Dynamic so no Xaml there For Auto complete My All Works Is to be Complete But i m Facing Same Tab order problem How Can I convert Above Xaml Code From C#
ctrl = new AutoCompleteBox { FontSize = 14, MaxDropDownHeight = 90 };
//Here We need to Implement That Style
ctrl.TabIndex = c.TabOrder;
ctrl.MaxWidth = 200;
if (c.SpName != null && c.DisplayMember != null)
{
DataTable dt = sqlHelper.ExecuteSelectProcedure(c.SpName);
var cmb = ctrl as AutoCompleteBox;
cmb.ItemsSource = dt.AsEnumerable().Select(r => r.Field<string>(c.DisplayMember)).ToList();
}
Please Help Me out Thanks And Regards
Shashank Tyagi
there is an application which you can do that, which is XamlT.
On WPF/SL apps, you can use XAML or C#/VB.NET code on some aspects (for example, to create an storyboard or set the image source).
Best regards
var style = new Style(typeof(TextBox));
var binding = new Binding("TabIndex") { ElementName = "txtFirstName" };
var setter = new Setter(TextBox.TabIndexProperty, binding);
style.Setters.Add(setter);
ctrl.TextBoxStyle = style;
else if (c.Type == typeof(AutoCompleteBox))
{
//var style = new Style(typeof(TextBox));
ctrl = new AutoCompleteBox { FontSize = 14, MaxDropDownHeight = 90, Name = c.ControlID };
ctrl.TabIndex = c.TabOrder;
ctrl.MaxWidth = 200;
var style = new Style(typeof(TextBox));
var binding = new Binding("TabIndex") { ElementName = c.ControlID };
var setter = new Setter(TextBox.TabIndexProperty, binding);
style.Setters.Add(setter);
(ctrl as AutoCompleteBox).TextBoxStyle = style;
if (c.SpName != null && c.DisplayMember != null)
{
DataTable dt = sqlHelper.ExecuteSelectProcedure(c.SpName);
var cmb = ctrl as AutoCompleteBox;
cmb.ItemsSource = dt.AsEnumerable().Select(r => r.Field<string>(c.DisplayMember)).ToList();
}
}
This Code Perfectly works

How to retrieve an element from a DataTemplate and bind to it?

I am trying to get a handle on an element within my DataTemplate in code. I am creating a series of DataGridTemplateColumns in code which I then assign to a grid.
I want to be able to retrieve the DataTemplate from the xaml, find my element and bind to that particular element.
Here is a short sample code what I am trying to achieve:
<DataTemplate x:Key="dataTemplate">
<Grid TextBlock.Foreground="LightGreen" Background="Yellow">
<TextBlock x:Name="txt" />
</Grid>
</DataTemplate>
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Last Name";
Binding b = new Binding("LastName");
DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
TextBlock textBlock = dtemplate.FindName("txt", this);
textBlock.SetBinding(TextBlock.TextProperty, b);
col.CellTemplate = dtemplate;
grid.Columns.Add(col);
Maybe to explain this further:
I am trying to create a set of DataGridTemplateColumns on the fly and apply that to a Datagrid. Since I don't know the property to bind to until the time a source gets presented to me I cannot create a DataTemplate that nested within itself has this binding already build in. Like:
<TextBlock Text={Binding=LastName} ... >
So I am forced to create a set of DataGridTemplateColumn in runtime, look for DataTemplate in my resources and THEN try to bind that column to a property (like LastName) on my datasource.
I would approach this via CellStyle instead:
<DataGrid.Resources>
<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="TextBlock.Foreground" Value="LawnGreen"/>
<Setter Property="Background" Value="Yellow"/>
</Style>
</DataGrid.Resources>
DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding("Name");
col.CellStyle = dataGrid.Resources["CellStyle"] as Style;
dataGrid.Columns.Add(col);
There are also ways to do this via DataTemplates but it does not seem necessary in this case (unless your problem is more complex).
My solution to the problem is something like this:
GridView viewLayout = new GridView();
for (int i = 0; i < Apprefs.tables[0].Headers.Count(); i++)
{
GridViewColumn gvc = new GridViewColumn();
string colName = Apprefs.tables[0].Headers[i];
gvc.Header = colName;
gvc.Width = 80;
gvc.CellTemplate = SetTemplete(i); ;
viewLayout.Columns.Add(gvc);
}
listview1.View = viewLayout;
//set binding
listview1.ItemsSource = Apprefs.tables[0].Rows;
and then:
/// <summary>
/// Create DataTemplate
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private DataTemplate SetTemplete(int i)
{
DataTemplate template = new DataTemplate();
//set stack panel
FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
sp.Name = "spBind";
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
//set textblock
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
sp.Name = "tbBind";
Binding b = new Binding();
string ito = "[" + i.ToString() + "]"; // bind by index
b.Path = new PropertyPath(ito);
tb.SetBinding(TextBlock.TextProperty, b);
sp.AppendChild(tb);
//set the visual tree of the data template
template.VisualTree = sp;
return template;
}

Categories

Resources