Create ListBox DataTemplate in C# - c#

I am trying to create a generic view, and I want it to contain a ListBox with a datatemplate
I want to create it either using pure C# code or if possible load it through xaml? If I can create a template I can get in c# as a resource of sorts.
What I have made until now is
private static ListBox CreateDayListBox()
{
var listBox = new ListBox();
var dataTemplate = new DataTemplate();
var grid = new Grid();
var columnDefinition1 = new ColumnDefinition {Width = GridLength.Auto};
var columnDefinition2 = new ColumnDefinition();
grid.ColumnDefinitions.Add(columnDefinition1);
grid.ColumnDefinitions.Add(columnDefinition2);
var rectangleItemBought = new Rectangle {Width = 50, Height = 50};
rectangleItemBought.SetBinding(Rectangle.FillProperty, new Binding("Bought"));
grid.Children.Add(rectangleItemBought);
var textBlockItemName = new TextBlock();
textBlockItemName.SetBinding(TextBlock.TextProperty, new Binding("Name"));
var textBlockItemQuantity = new TextBlock();
textBlockItemQuantity.SetBinding(TextBlock.TextProperty, new Binding("Quantity"));
var textBlockItemQuantityType = new TextBlock();
textBlockItemQuantityType.SetBinding(TextBlock.TextProperty, new Binding("QuantityType"));
var stackpanel = new StackPanel();
Grid.SetColumn(stackpanel, 1);
stackpanel.Children.Add(textBlockItemName);
stackpanel.Children.Add(textBlockItemQuantity);
stackpanel.Children.Add(textBlockItemQuantityType);
grid.Children.Add(stackpanel);
return listBox;
}
So I want the listbox datatemplate to contain 1 rectangle, 1 stackpanel with 3 textboxes inside

You can write the template in XAML then load it in your code.
Read this.
Besides, I'm pretty sure you can create the DataTemplate by code the same way you created the controls, look at this code (credit):
DataTemplate template = new DataTemplate();
FrameworkElementFactory factory =
new FrameworkElementFactory(typeof(StackPanel));
template.VisualTree = factory;
FrameworkElementFactory childFactory =
new FrameworkElementFactory(typeof(Image));
childFactory.SetBinding(Image.SourceProperty, new Binding("Machine.Thumbnail"));
childFactory.SetValue(Image.WidthProperty, 170.0);
childFactory.SetValue(Image.HeightProperty, 170.0);
factory.AppendChild(childFactory);
childFactory = new FrameworkElementFactory(typeof(Label));
childFactory.SetBinding(Label.ContentProperty,
new Binding("Machine.Descriiption"));
childFactory.SetValue(Label.WidthProperty, 170.0);
childFactory.SetValue(Label.HorizontalAlignmentProperty,
HorizontalAlignment.Center);
factory.AppendChild(childFactory);

Related

Interaction.GetBehaviors from FrameworkElementFactory type combobox

I'm trying to hide a dynamic combobox what is set from FrameworkElementFactory.
If i try Combobox as parameter then i get the error 'ComboBox' is a type, which is not valid in the given context and if i try fElement as parameter then it gives the error "cannot convert from 'System.Windows.FrameworkElementFactory' to 'System.Windows.DependencyObject'" I need the solution in C# not in xaml or ASP.net.
FrameworkElementFactory fElement = new FrameworkElementFactory(typeof(ComboBox));
fElement.SetValue(ComboBox.WidthProperty, 125D);
fElement.SetValue(ComboBox.ItemsSourceProperty, choices);
fElement.SetValue(ComboBox.DisplayMemberPathProperty, "Value");
fElement.SetValue(ComboBox.SelectedValuePathProperty, "Value");
fElement.SetValue(ComboBox.NameProperty, "CONAAM" + rowOnderdeel.OnderdeelID);
//fElement.SetValue(ComboBox.NameProperty, Onderdeelnaam);
fElement.AddHandler(Selector.SelectionChangedEvent, new SelectionChangedEventHandler(cbCursistOnderdeelResultaat));
fElement.SetBinding(ComboBox.TextProperty, bind);
Interaction.GetBehaviors(ComboBox).Add(new HideComboxBehavior());
Solutions was to use System.Windows.Style and use setter to trigger the visibility of the combobox.
FrameworkElementFactory fElement = new FrameworkElementFactory(typeof(ComboBox));
fElement.SetValue(ComboBox.WidthProperty, 125D);
fElement.SetValue(ComboBox.ItemsSourceProperty, Resultaten);
fElement.SetValue(ComboBox.DisplayMemberPathProperty, "Value");
fElement.SetValue(ComboBox.SelectedValuePathProperty, "Key");
fElement.SetValue(ComboBox.SelectedValueProperty, new Binding(column.ColumnName));
Style cbStyle = new Style(typeof(ComboBox));
Setter cbSetter = new Setter(ComboBox.VisibilityProperty, Visibility.Visible);
cbStyle.Setters.Add(cbSetter);
DataTrigger cbDataTrigger = new DataTrigger();
Binding cbBinding = new Binding(column.ColumnName);
cbDataTrigger.Value = 0;
Setter cbDataSetter = new Setter(ComboBox.VisibilityProperty, Visibility.Hidden);
cbDataTrigger.Setters.Add(cbDataSetter);
cbDataTrigger.Binding = cbBinding;
cbStyle.Triggers.Add(cbDataTrigger);
fElement.SetValue(ComboBox.StyleProperty, cbStyle);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = fElement;
gvc.CellTemplate = dataTemplate;

How to customize a tooltip for each individual datapoint in a wpf toolkit lineseries chart?

I have seen several questions about doing a custom tooltip for a single line series.
I need a custom tool-tip for each data-point. I would like to add more to the tool-tip than just the dependent value path and the independent value path.
Example I have 2 data points on the same line one with a value(Y-axis)
of 2, date(x-axis) of 4/28/2016, and configuration of A. The other has
a value of 3, date of 4/29/2016, and configuration of B.
How would I also show the configurations? This is all done in code behind because I have a dynamic number of lineseries. So I can't just assign a style to each lineseries in the xaml.
var MyLineSeries = new LineSeries();
lMyLineSeries.DependentValuePath = "Y";
lMyLineSeries.IndependentValuePath = "X";
lMyLineSeries.DataPointStyle = lToolTipDataPointStyle;
This is my code for creating the tool tip style.
var lToolTipDataPointStyle = new Style(typeof(LineDataPoint));
var lTemplate = new ControlTemplate(typeof(LineDataPoint));
var lGridElement = new FrameworkElementFactory(typeof(Border));
//Tooltip
var lStackPanel = new StackPanel();
var lValueContentControl = new ContentControl();
lValueContentControl.SetBinding(ContentControl.ContentProperty, new Binding(myLineSeries.DependentValuePath));
lValueContentControl.ContentStringFormat = "Value: {0}";
var lConfigurationContentControl = new ContentControl();
lConfigurationContentControl.SetBinding(ContentControl.ContentProperty, new Binding())//This is what Idk what to bind to???
lConfigurationContentControl.ContentStringFormat = "Configuration: {0}";
lStackPanel.Children.Add(lValueContentControl);
lStackPanel.Children.Add(lConfigurationContentControl);
lGridElement.SetValue(ToolTipService.ToolTipProperty, lStackPanel);
var lEllipseElement = new FrameworkElementFactory(typeof(Ellipse));
lEllipseElement.SetValue(Ellipse.StrokeThicknessProperty, new TemplateBindingExtension(Border.BorderThicknessProperty));
lEllipseElement.SetValue(Ellipse.StrokeProperty, new TemplateBindingExtension(Border.BorderBrushProperty));
lEllipseElement.SetValue(Ellipse.FillProperty, new TemplateBindingExtension(Grid.BackgroundProperty));
lGridElement.AppendChild(lEllipseElement);
lTemplate.VisualTree = lGridElement;
var lTemplateSetter = new Setter();
lTemplateSetter.Property = LineDataPoint.TemplateProperty;
lTemplateSetter.Value = lTemplate;
lToolTipDataPointStyle.Setters.Add(lTemplateSetter);
return lToolTipDataPointStyle;
I figured it out by using the Tag on the Line series.
myLineSeries.Tag = "Configuration";
var lConfigurationContentControl = new ContentControl();
lConfigurationContentControl.SetBinding(ContentControl.ContentProperty, new Binding(myLineSeries.Tag.ToString()))
lConfigurationContentControl.ContentStringFormat = "Configuration: {0}";

Bindings on Datagrids in code Behind

I'm working on a cookbook for myself, written in WPF/C#.
Additionally I'm new to Data Bindings.
My Problem is, I want to generate a Datagrid in a TabItem on runtime in code behind, including Bindings. I can't set a Datagrid at XAML because I want to create all TabItems dynamically.
Following Code so far:
XAML:
<UniformGrid Columns="2" Rows="1">
<TabControl Name="TabControl" TabStripPlacement="Left"/>
<TabItem Header= "first dish" Name = "firstdish"/>
</UniformGrid>
XAML.cs for generation:
//New Grid
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
firstdish.Content = Grid;
All I'm getting is an datagrid with four rows (looks like the count of Items is right), which are all empty, no data to be seen.
I'm staring at this since last Weeks Monday and can't find an answer anywhere.
Thanks for any ideas and solutions.
try changing
var TestList = new List<Receipt>();
to
var TestList = new ObservableCollection<Receipt>();
as it automatically notifies UI about changes.
I had a similar problem with items not rendering so this may be it.
I've taken your code and checked some of the things you do: The main error is that in your xaml code you created the Tab Control and then Put the TabItem outside it, Tabitem must be inside the control for it to work correctly. so First error is:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header="First dish" Name = "firstdish" />
</TbControl>
Other things you need to do before going on in my opinion are:
Assign your window or other UI element itself as datacontext
Verify that your Receipt class implements the INotifyPropertyChanged event that has to be raised by all its properties, or implement your properties as DependencyProperties (even if the latter is not necessary)
Transform your datasource TestList in an ObservableCollection
Create TestList as a class property not a local variable so that it is into the datacontext
I've made a small sample using the above indication and your code to let you see better how that works. You can download the zip here:
TestClassDataGrid.zip
Below code should work for you,
XAML:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header= "first dish" Name = "firstdish"/>
</TabControl>
.cs file
public Window()
{
InitializeComponent();
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
Grid.AutoGenerateColumns = false;
firstdish.Content = Grid;
}

The same object 2 time in datagrid

I got a problem with my datagrid. When i click on an element my row become selected and my selected style apply.
but when i scroll, if the element is there again (not duplicate value, item reference are the same), it become in blue, like selected default style.
Having the same item highlight is not a problem, but i would like to put my selected style (the violet dot in row header). In debug, the rows in blue are not selected (and if they were my style would apply). What is the property for being highlight for the duplicate object.
Edit
Binding oBindRowSelected = new Binding();
Binding oBindCellSelected = new Binding();
Binding oBindBackGround = new Binding();
Binding oBindBorderBrush = new Binding();
Binding oBindForeGround = new Binding();
oBindRowSelected.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridRow), 1);
oBindCellSelected.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridCell), 1);
oBindRowSelected.Path = new PropertyPath(DataGridRow.IsSelectedProperty);
oBindCellSelected.Path = new PropertyPath(DataGridCell.IsSelectedProperty);
oBindBackGround.Path = new PropertyPath(DataGridRow.BackgroundProperty);
oBindBorderBrush.Path = new PropertyPath(DataGridRow.BorderBrushProperty);
oBindForeGround.Path = new PropertyPath(DataGridRow.ForegroundProperty);
DataTrigger oTriggerSelectedImageVisibility = new DataTrigger();
oTriggerSelectedImageVisibility.Binding = oBindRowSelected;
oTriggerSelectedImageVisibility.Value = true;
oTriggerSelectedImageVisibility.Setters.Add(new Setter(Border.VisibilityProperty, Visibility.Visible));
DataTrigger oTriggerSelectedCell = new DataTrigger();
oTriggerSelectedCell.Binding = oBindRowSelected;
oTriggerSelectedCell.Value = true;
oTriggerSelectedCell.Setters.Add(new Setter(DataGridCell.BackgroundProperty, oBindBackGround));
oTriggerSelectedCell.Setters.Add(new Setter(DataGridCell.BorderBrushProperty, oBindBorderBrush));
oTriggerSelectedCell.Setters.Add(new Setter(DataGridCell.ForegroundProperty, oBindForeGround));
Style oRowHeaderSelectorStyle = new Style(typeof(Border));
oRowHeaderSelectorStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(7)));
oRowHeaderSelectorStyle.Setters.Add(new Setter(Border.HeightProperty, 15.0));
oRowHeaderSelectorStyle.Setters.Add(new Setter(Border.WidthProperty, 15.0));
oRowHeaderSelectorStyle.Setters.Add(new Setter(Border.BackgroundProperty, Brushes.BlueViolet));
oRowHeaderSelectorStyle.Setters.Add(new Setter(Border.VisibilityProperty, Visibility.Hidden));
oRowHeaderSelectorStyle.Triggers.Add(oTriggerSelectedImageVisibility);
ControlTemplate oCtlTemplate = new ControlTemplate();
FrameworkElementFactory oBorder = new FrameworkElementFactory(typeof(Border));
oBorder.SetValue(Border.StyleProperty, oRowHeaderSelectorStyle);
oCtlTemplate.VisualTree = oBorder;
Style oRowHeaderStyle = new Style(typeof(DataGridRowHeader));
oRowHeaderStyle.Setters.Add(new Setter(DataGridRowHeader.WidthProperty, 25.0));
oRowHeaderStyle.Setters.Add(new Setter(DataGridRowHeader.TemplateProperty, oCtlTemplate));
Style oCellStyle = new Style(typeof(DataGridCell));
oCellStyle.Triggers.Add(oTriggerSelectedCell);
this.RowHeaderStyle = oRowHeaderStyle;
this.CellStyle = oCellStyle;
I am working in an extension, so my style is in C# code.

New TabItem at run time

Hi I am using TabControl to make Conference System, the private chats would be in a new TabItem. I am using this code to present a new member chatting in private:
TabItem ti = new TabItem();
ti.Header="Name";
MyTabControl.Items.Add(ti);
but the problem with this code is that I am adding a list box in the TabItem but the TabItem doesn't have a function to add an item in it. how can I add items into TabItem?
Second try: I used this code to present a new member chatting in private
ItemsControl it = new ItemsControl();
ListBox lst = new ListBox();
lst.Width = 571;
lst.Height = 301;
it.Items.Add(lst);
tabControlChat.Items.Add(it);
with this code I can add all items I need in the new tab. but the main problem is that I can't name the tab there is no property like (ti.Header) to name the tab. so what is the solution please? and thank you
For short:
ListBox lb = new ListBox();
lb.Items.Add("chat member");
TabItem ti = new TabItem();
ti.Header = "Private Chats";
ti.Content = lb;
TabControl tc = new TabControl();
tc.Items.Add(ti);
Use this:
TabItem ti = new TabItem();
ti.Header = "Name";
tabControl1.Items.Add(ti);
ListBox lst = new ListBox();
lst.Width = 571;
lst.Height = 301;
ti.Content = lst;

Categories

Resources