convert xaml template binding to code behind - c#

I have a gridcontrol which is populated from database. Also, in code, I added to datatable a checkeditsettings column. I created a template in xaml , but I can't manage to convert it in C#. In my code below,
XAML code:
<dxg:GridColumn FieldName="Select" Fixed="Right" UnboundType="Boolean">
<dxg:GridColumn.EditSettings>
<dxe:CheckEditSettings />
</dxg:GridColumn.EditSettings>
<dxg:GridColumn.CellTemplate>
<DataTemplate>
<local:MyCheckEdit
IsChecked="False"
IsEnabled='True'
Checked="MyCheckEdit_Checked"
EnabledChecked="/Images/mark.png"
EnabledUnchecked="/Images/markk.png"
DisabledUnchecked="/Images/marken.png" >
</local:MyCheckEdit>
</DataTemplate>
</dxg:GridColumn.CellTemplate>
</dxg:GridColumn>
What I have tried so far:
GridColumn colselect = new GridColumn();
ComboBoxEditSettings c = new ComboBoxEditSettings();
colselect.EditSettings = c;
DataTemplate template = new DataTemplate();
template.VisualTree = new FrameworkElementFactory(typeof(MyCheckEdit));
template.VisualTree.SetBinding(MyCheckEdit.ContentProperty, new Binding("...?"));
colselect.CellTemplate = template;
I am really stack here.

Keep the DataTemplate in a Resources section in xaml, give it a name (x:Key) and just reference it from code-behind when you need it:
<dxg:DataGrid x:name="myGrid" >
<dxg:DataGrid.Resources>
<DataTemplate x:Key="MyCellTemplate" >
<local:MyCheckEdit IsChecked="False"
IsEnabled='True'
Checked="MyCheckEdit_Checked"
EnabledChecked="/Images/mark.png"
EnabledUnchecked="/Images/markk.png"
DisabledUnchecked="/Images/marken.png" />
</DataTemplate>
</dxg:DataGrid.Resources>
...
</dxg:DataGrid>
Then, in your code-behind:
GridColumn colselect = new GridColumn();
colselect.EditSettings = new ComboBoxEditSettings();
colselect.CellTemplate = myGrid.Resources["MyCellTemplate"] as DataTemplate;

Related

UWP GridView in C# with DataTemplate

I have a Grid where I want to put a GridView in every cell of it from the code-behind in the .xaml.cs. The problem is that I do not know how to create a GridView with a DataTemplate to bind stuff in it in C#
DataTemplate Template= new DataTemplate();
GridView gridView = new GridView();
gridView.ItemsSource = book;
Thats all I have. Help is appreciated
J.
I want to put a GridView in every cell of it from the code-behind in the .xaml.cs.
You could make a DataTemplate in App.xaml file like follow.
<Application.Resources>
<ResourceDictionary>
<DataTemplate x:Key="template">
<StackPanel>
<TextBlock Text="{Binding }"/>
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</Application.Resources>
And use it in the code behind.
private void SetUpUI()
{
var gridView = new GridView();
//DataTemplate usage.
gridView.ItemTemplate = (DataTemplate)App.Current.Resources["template"];
gridView.ItemsSource = new List<string> { "fas", "fasd", "fasf" };
RootLayout.Children.Add(gridView);
}

Textboxes binded to SelectedItem of a code-behind created DataGrid don't actualize

I'm experimenting with code-behind created WPF masks as prototype for a WPF mask designer.
In my ViewModel i have a DataTable and a DataView (which is simply the DefaultView of the DataTable).
In my DataTable i got two columns ("vorname" and "nachname") and four rows.
In my WPF mask i want to have a DataGrid and two TextBoxes, which are binded to the SelectedItem of the DataGrid and the columns (either "vorname" or "nachname").
When i select an item in the DatGrid at runtime, the data from that item shall be showed in the TextBoxes.
First i tried to define the DataGrid in the XAML file and generate the TextBoxes an their bindings in code.
Here it works fine.
I select an item in the DataGrid and the data of the item is showed in the TextBoxes.
But when i generate the grid in code, it doesn't work anymore.
Is there some sort of NotifyOnSelectedIndexChanged, that i'm missing?
Any help will be appreciated.
This is the XAML:
<Window x:Class="DesignerTest.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow"
Height="400"
Width="600">
<DockPanel x:Name="mainpanel">
<!--<DataGrid x:Name="datagrid"
DockPanel.Dock="Top"
Height="120" />-->
<WrapPanel x:Name="wrappanel">
<!--<TextBox x:Name="vornameSelected" Width="150" Margin="5" Text="{Binding SelectedItem.vorname, ElementName=datagrid}" IsEnabled="False" />
<TextBox x:Name="nachnameSelected" Width="150" Margin="5" Text="{Binding SelectedItem.nachname, ElementName=datagrid}" IsEnabled="False" />-->
<!--<TextBox x:Name="vornameSelected" Width="150" Margin="5" IsEnabled="False" />
<TextBox x:Name="nachnameSelected" Width="150" Margin="5" IsEnabled="False" />-->
</WrapPanel>
</DockPanel>
</Window>
And this is the code for creating and binding:
// The ViewModel und the DataTable are created.
_vm = new SerializingTestViewModel();
_vm.CreateDataTable();
this.DataContext = _vm.DataTable;
// The DataGrid and it's Binding are created.
DataGrid datagrid = new DataGrid();
datagrid.Name = "datagrid";
DockPanel.SetDock(datagrid, Dock.Top);
datagrid.Height = 120;
datagrid.ItemsSource = _vm.DataSource;
mainpanel.Children.Add(datagrid);
// The Textboxes and the Bindings are created.
TextBox vornameSelected = new TextBox();
vornameSelected.Name = "vornameSelected";
vornameSelected.Width = 150;
Thickness margin = new Thickness(5);
vornameSelected.SetValue(TextBox.MarginProperty, margin);
vornameSelected.IsEnabled = false;
Binding selectedItemBinding = new Binding();
selectedItemBinding.ElementName = "datagrid";
selectedItemBinding.Path = new PropertyPath("SelectedItem.vorname");
vornameSelected.SetBinding(TextBox.TextProperty, selectedItemBinding);
wrappanel.Children.Add(vornameSelected);
TextBox nachnameSelected = new TextBox();
nachnameSelected.Name = "nachnameSelected";
nachnameSelected.Width = 150;
margin = new Thickness(5);
nachnameSelected.SetValue(TextBox.MarginProperty, margin);
nachnameSelected.IsEnabled = false;
selectedItemBinding = new Binding();
selectedItemBinding.ElementName = "datagrid";
selectedItemBinding.Path = new PropertyPath("SelectedItem.nachname");
nachnameSelected.SetBinding(TextBox.TextProperty, selectedItemBinding);
wrappanel.Children.Add(nachnameSelected);
Try setting your binding source using the Source property instead of ElementName
//selectedItemBinding.ElementName = "datagrid"
selectedItemBinding.Source = datagrid;
The problem might be that the ElementName lookup for items is not working as expected because items are added dynamically at runtime via code behind.

Adding button on WPF data grid rows from codebehind c# code

I want to add a button on every row of WPF grid which I am binding from code behind. I am very new to WPF any help is appreciated.
My current code for binding grid is:
DataGridTextColumn c1 = new DataGridTextColumn();
c1.Header = "Dummy column";
c1.Binding = new Binding("DummyColumn");
c1.IsReadOnly = true;
grdDummy.Columns.Add(c1);
foreach (DummyObject deal in AllDummyObjects)
{
ModelToBind dataModel = new ModelToBind()
//do some processing on dataModel
grdDummy.Items.Add(dataModel);
}
You can add another column with button like this:
DataGridTemplateColumn buttonColumn = new DataGridTemplateColumn();
DataTemplate buttonTemplate = new DataTemplate();
FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof (Button));
buttonTemplate.VisualTree = buttonFactory;
//add handler or you can add binding to command if you want to handle click
buttonFactory.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(HandleClick));
buttonFactory.SetValue(ContentProperty, "Button");
buttonColumn.CellTemplate = buttonTemplate;
grdDummy.Columns.Add(buttonColumn);
Previously, an example was given of creating a Button using FrameworkElementFactory.
This class is not recommended.
Quote from the documentation:
This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
In this regard, I show the implementation code using the XamlReader.
The code is shown from the assumption that the ModelToBind class has a command-property named ButtonCommand and property ButtonTitle.
And this class is located in the local namespace "Febr20y" in the assembly of the same name.
DataGridTextColumn c1 = new DataGridTextColumn
{
Header = "Dummy column",
Binding = new Binding("DummyColumn"),
IsReadOnly = true
};
DataTemplate template = (DataTemplate)XamlReader.Parse(
#"<DataTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Febr20y;assembly=Febr20y'
DataType ='{x:Type local:ModelToBind}'>
<Button Content='{Binding ButtonTitle, Mode=OneWay}'
Command='{Binding ButtonCommand, Mode=OneWay}'/>
</DataTemplate>");
DataGridTemplateColumn c2 = new DataGridTemplateColumn()
{
Header = "Buttons",
IsReadOnly = true,
CellTemplate=template
};
grdDummy.Columns.Add(c1);
grdDummy.Columns.Add(c2);
var listSource = AllDummyObjects
.Select(deal => new ModelToBind() { ButtonTitle = deal.Title.ToString()})
.ToList();
grdDummy.ItemsSource = listSource;
This is equivalent to this XAML code:
<DataGrid x:Name="grdDummy" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding DummyColumn}"
IsReadOnly="True"
Header="Dummy column"/>
<DataGridTemplateColumn Header="Buttons"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type local:ModelToBind}">
<Button Content="{Binding ButtonTitle, Mode=OneWay}"
Command="{Binding ButtonCommand, Mode=OneWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

How to convert XAML(ControlTemplate) to Code-Behind

<dxg:LookUpEdit Margin="5" HorizontalAlignment="Stretch" VerticalAlignment="Center"
ItemsSource="{Binding}"
DisplayMember="Name"
AutoPopulateColumns="False">
<dxg:LookUpEdit.PopupContentTemplate>
<ControlTemplate>
<dxg:GridControl Name="PART_GridControl">
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="Name"/>
<dxg:GridColumn FieldName="Date"/>
</dxg:GridControl.Columns>
</dxg:GridControl>
</ControlTemplate>
</dxg:LookUpEdit.PopupContentTemplate>
</dxg:LookUpEdit>
please help me, I do not know how to add GridColumn on GridControl and set LookUpEdit.PopupContentTemplate = GridControl
Thank you very much. I think XAMLREADER can help me, I'm stuck here
ControlTemplate ct = new ControlTemplate();
FrameworkElementFactory gridcontrol = new FrameworkElementFactory(typeof(GridControl));
FrameworkElementFactory gridcolumn = new FrameworkElementFactory(typeof(GridColumn));
gridcontrol.SetValue(?, ?);
gridcolumn.SetValue(?, ?);
ct.VisualTree = gridcontrol;
creating control/data templates in code behind involves factory classes, that may be more complicated for non framework types.
example from Creating a control template with code behind
ControlTemplate template = new ControlTemplate(typeof(ListBoxItem));
FrameworkElementFactory elemFactory = new FrameworkElementFactory(typeof(Border));
elemFactory.Name = "Border";
elemFactory.SetValue(Border.CornerRadiusProperty, new CornerRadius(5));
elemFactory.SetValue(Border.PaddingProperty, new Thickness(1));
elemFactory.SetValue(Border.SnapsToDevicePixelsProperty, true);
template.VisualTree = elemFactory;
//same can be used as
LookUpEdit.PopupContentTemplate = template;
above is just an example, you may need to use the appropriate types
alternatively keeping the control templates in resource dictionary may help you
or the easiest solution is to parse the xaml in code behind
const string xaml = "<ControlTemplate><dxg:GridControl Name=""PART_GridControl""><dxg:GridControl.Columns><dxg:GridColumn FieldName=""Name""/><dxg:GridColumn FieldName=""Date""/></dxg:GridControl.Columns></dxg:GridControl></ControlTemplate>";
ControlTemplate template = XamlReader.Parse(xaml) as ControlTemplate;
//this can be used as
LookUpEdit.PopupContentTemplate = template;

nested xaml elements - rewrite it in code

I need to create a DataGridColumn from code.
The XAML equivalent would be:
<data:DataGridTemplateColumn Header="Name" Width="100">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis"></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
I've started like that:
DataGridTemplateColumn column = new DataGridTemplateColumn
{
Header = "Name",
Width = 100,
};
TextBlock inside = new TextBlock {TextTrimming = TextTrimming.CharacterEllipsis};
But I don't know how to 'merge' such puzzles. There are nested elements in XAML, how to achieve this from code?
A good way to do this is to pack the entire XAML snippet into a string and call XamlReader.Load() or XamlReader.Parse() on it. The bonus feature of this approach is that it'll work in Silverlight as well (with some fiddling), where you can't build DataTemplates in code.
Almost there, change your code to this and it should work:
DataGridTemplateColumn column = new DataGridTemplateColumn
{
Header = "Name",
Width = 100,
};
FrameworkElementFactory ftb = new FrameworkElementFactory(typeof(TextBlock));
Binding b = new Binding("Name");
ftb.SetValue(TextBlock.Text, b);
ftb.SetValue(TextBlock.TextTrimming, TextTrimming.CharacterEllipsis);
DataTemplate ct = new DataTemplate();
ct.VisualTree = ftb;
column.CellTemplate = ct;
Another method besides the above is to define your datatemplate in XAML within your resources then dynamically load it in the code:
XAML:
<Window.Resources>
<DataTemplate x:Key="myCellTemplate">
<TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis" />
</DataTemplate>
</Window.Resources>
Code:
DataGridTemplateColumn column = new DataGridTemplateColumn
{
Header = "Name",
Width = 100,
};
column.CellTemplate = this.FindResource("myCellTemplate") as DataTemplate;

Categories

Resources