Selected item not showing in a WPF combobox - wpf

I'm creating a part of my window in code. For a combobox I do this:
ObservableCollection<ParamClassOption> options = new ObservableCollection<ParamClassOption>(
context.ParamClassOptions.Where(x => x.IDParamClass == val.CompTypeParam.IDParamClass));
ComboBox combobox = new ComboBox();
combobox.Name = "combobox" + val.CompTypeParam.ParameterName.Replace(" ", "");
combobox.ItemsSource = options;
combobox.SelectedValuePath = "IDParamClass";
combobox.DisplayMemberPath = "OptionName";
if (val.ParamClassOption != null)
{
combobox.SelectedValue = val.ParamClassOption.IDParamClassOption;
}
layoutitem.Content = combobox;
I'm able to select an item from the list and save it to the database. The problem that I have is to show the saved value again upon retrieving the values back from the database. Any idea why it's not showing? val.ParamClassOption.IDParamClassOption in the second to last line above has the correct value when the record is retrieved to be displayed.

i think you forgot to bind your selected value
var binding = new Binding {Path = new PropertyPath("IDParamClassOption"), Mode = BindingMode.TwoWay, Source = val.ParamClassOption};
combobox.SetBinding(ComboBox.SelectedValueProperty, binding);
hope this helps

Thanks for the help. I ended up using a completely different approach by adding the items to the combo-box one by one. I then set the selected item to previously added value (using the Text property). Here is what my code looks like now:
if (controlType == "Combobox")
{
ComboBox combobox = new ComboBox();
combobox.Name = "combobox" + val.CompTypeParam.ParameterName.Replace(" ", "");
ObservableCollection<ParamClassOption> options = new ObservableCollection<ParamClassOption>(
context.ParamClassOptions.Where(x => x.IDParamClass == val.CompTypeParam.IDParamClass));
combobox.Items.Clear();
foreach (ParamClassOption option in options)
{
ComboBoxItem item = new ComboBoxItem();
item.Content = option.OptionName;
combobox.Items.Add(item);
}
combobox.Text = val.ParamClassOption.OptionName;
layoutitem.Content = combobox;
}
Later when reading the value from the combobox to save to the database I did this:
ObservableCollection<ParamClassOption> option = new ObservableCollection<ParamClassOption>(
context.ParamClassOptions.Where(o => o.IDParamClass == value.CompTypeParam.IDParamClass).Where(o => o.OptionName == combobox.Text));
value.IDParamClassOption = option[0].IDParamClassOption;

Related

.NET WPF set combobox selected item

I am setting items in a combobox with this:
Dictionary<int, string> myItems = await resp.Content.ReadAsAsync<Dictionary<int, string>>();
myCmb.Items.Clear();
myCmb.ItemsSource = myItems;
myCmb.SelectedValuePath = "Key";
myCmb.DisplayMemberPath = "Value";
Then I want to select item by Key (for example, select item with Key=5) in another part of the code. How can this be done?
myCmb.SelectedItem = myItems.FirstOrDefault(n => n.Key == desiredKey);
You can do it this way but you will need to have myItems accessible from the another part of code.

how can i show multiple indenepdent template in top level of telerik radgridview

hello:
i want add multiple template to radgridview and show templates in tabbed style ,
my templates is independent and no relation to each other,
when i add templates to masterTemplate and set datasource of my templates,
datagrid is show empty grid and templates is not visible.
some tried code :
Add Template Section:
GridViewTemplate gvt = new GridViewTemplate();
gvt.AllowDeleteRow = false;
gvt.AllowEditRow = false;
gvt.ShowTotals = true;
gvt.Caption = SubCaption[i];
radResult.MasterTemplate.Templates.Add(gvt);
radResult.Refresh();
Set Data Source Section that Indexnumber is template index:
radResult.MasterTemplate.Templates[IndexNumber].DataSource = dtl;
radResult.MasterTemplate.Templates[IndexNumber].Refresh();
radResult.Refresh();
my desired View is :
RadGridView target view
how must i do that?
thanks advance
RadGridView offers only one master level via the MasterGridViewTemplate. You can add as many child GridViewTemplates to the master level as you need. More information is available here: https://docs.telerik.com/devtools/winforms/controls/gridview/hierarchical-grid/hierarchy-of-one-to-many-relations
However, this requires a relation between the MasterTemplate and each of the child GridViewTemplates.
In order to achieve your design from the screenshot for a tabbed view in RadGridView on the parent level, I can suggest the following approaches:
Use a single RadGridView instance and set up a hierarchy with load on demand. For this purpose, it would be necessary to add a dummy row for the master level and keep it expanded. The following code snippet shows how to achieve it:
private void RadForm1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'nwindDataSet.Products' table. You can move, or remove it, as needed.
this.productsTableAdapter.Fill(this.nwindDataSet.Products);
// TODO: This line of code loads data into the 'nwindDataSet.Orders' table. You can move, or remove it, as needed.
this.ordersTableAdapter.Fill(this.nwindDataSet.Orders);
// TODO: This line of code loads data into the 'nwindDataSet.Categories' table. You can move, or remove it, as needed.
this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories);
this.radGridView1.MasterTemplate.Columns.Add("MasterLevel");
this.radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
this.radGridView1.MasterTemplate.AllowAddNewRow = false;
this.radGridView1.ShowColumnHeaders = false;
this.radGridView1.ShowGroupPanel = false;
GridViewTemplate childTemplateCategories = new GridViewTemplate();
childTemplateCategories.Caption = "Categories";
foreach (DataColumn col in this.nwindDataSet.Categories.Columns)
{
childTemplateCategories.Columns.Add(col.ColumnName);
}
childTemplateCategories.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
this.radGridView1.Templates.Add(childTemplateCategories);
childTemplateCategories.HierarchyDataProvider = new GridViewEventDataProvider(childTemplateCategories);
GridViewTemplate childTemplateProducts = new GridViewTemplate();
childTemplateProducts.Caption = "Products";
foreach (DataColumn col in this.nwindDataSet.Products.Columns)
{
childTemplateProducts.Columns.Add(col.ColumnName);
}
childTemplateProducts.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
this.radGridView1.Templates.Add(childTemplateProducts);
childTemplateProducts.HierarchyDataProvider = new GridViewEventDataProvider(childTemplateProducts);
GridViewTemplate childTemplateOrders = new GridViewTemplate();
childTemplateOrders.Caption = "Orders";
foreach (DataColumn col in this.nwindDataSet.Orders.Columns)
{
childTemplateOrders.Columns.Add(col.ColumnName);
}
childTemplateOrders.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
this.radGridView1.Templates.Add(childTemplateOrders);
childTemplateOrders.HierarchyDataProvider = new GridViewEventDataProvider(childTemplateOrders);
this.radGridView1.RowSourceNeeded += new GridViewRowSourceNeededEventHandler(radGridView1_RowSourceNeeded);
this.radGridView1.Rows.Add("Master");
this.radGridView1.Rows[0].IsExpanded = true;
}
private void radGridView1_RowSourceNeeded(object sender, GridViewRowSourceNeededEventArgs e)
{
if (e.Template.Caption == "Categories")
{
foreach (DataRow row in this.nwindDataSet.Categories.Rows)
{
GridViewRowInfo r = e.Template.Rows.NewRow();
foreach (GridViewCellInfo cell in r.Cells)
{
cell.Value = row[cell.ColumnInfo.Name];
}
e.SourceCollection.Add(r);
}
}
else if (e.Template.Caption == "Products")
{
foreach (DataRow row in this.nwindDataSet.Products.Rows)
{
GridViewRowInfo r = e.Template.Rows.NewRow();
foreach (GridViewCellInfo cell in r.Cells)
{
cell.Value = row[cell.ColumnInfo.Name];
}
e.SourceCollection.Add(r);
}
}
else if (e.Template.Caption == "Orders")
{
foreach (DataRow row in this.nwindDataSet.Orders.Rows)
{
GridViewRowInfo r = e.Template.Rows.NewRow();
foreach (GridViewCellInfo cell in r.Cells)
{
cell.Value = row[cell.ColumnInfo.Name];
}
e.SourceCollection.Add(r);
}
}
}
Use a RadDock or a RadPageView and add as many tabbed documents/pages as you need. Then, on each tab/page add a separate RadGridView control and populate it with the relevant data.
Feel free to use this approach which suits your requirements best.

TreeListLookupEdit - Focus Node

I'm trying to select a node in TreeListLookupEdit.
var fn = treeListLookupEdit1.FindNodeByKeyID(NodeId);
treeListLookupEdit1.Properties.TreeList.FocusedNode = fn;
My TreeListLookupEdit is already filled with the data (from an EF datasource), I need to focus the desired row and see this value in both treeListLookUpEdit1.Text (when it is in a closed state) and when I open a popup window too.
But nothing happens, it does not selects the node.
I've also tried this (Where "treeNodes" is the actual TreeList inside the TreeListLookupEdit):
treeNodes.FocusedNode = fn;
But, when I run this piece of code, it works:
treeListLookupEdit1.ShowPopup();
treeListLookupEdit1.Properties.TreeList.FocusedNode = fn;
treeListLookupEdit1.ClosePopup();
So, how to avoid using the ShowPopup?
Update
It seems, you should set EditValue
treeListLookupEdit1.EditValue = NodeId
You need to set up TreeListLookUpEdit.Properties.DisplayMember property and TreeListLookUpEdit.Properties.ValueMember property.
Set the TreeListLookUpEdit.Properties.DisplayMember property to the column that you want to display in your TreeListLookupEdit and TreeListLookUpEdit.Properties.ValueMember to ID column and use TreeListLookUpEdit.EditValue to focus node.
After that you can do something like this:
treeListLookupEdit1.EditValue = fn.GetValue("YourIDColumn");
Here is example with DataTable as data source:
var dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Parent_ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Rows.Add(1, null, "1");
dataTable.Rows.Add(2, null, "2");
dataTable.Rows.Add(3, null, "3");
dataTable.Rows.Add(4, 1, "1.1");
dataTable.Rows.Add(5, 1, "1.2");
dataTable.Rows.Add(6, 3, "3.1");
dataTable.Rows.Add(7, 3, "3.2");
dataTable.Rows.Add(8, 5, "1.2.1");
var treeListLookUpEdit = new TreeListLookUpEdit();
var properties = treeListLookUpEdit.Properties;
properties.DataSource = dataTable;
properties.DisplayMember = "Name";
properties.ValueMember = "ID";
var treeList = properties.TreeList;
treeList.KeyFieldName = "ID";
treeList.ParentFieldName = "Parent_ID";
treeList.RootValue = DBNull.Value;
Controls.Add(treeListLookUpEdit);
treeListLookUpEdit.Size = treeListLookUpEdit.CalcBestSize();
If you set EditValue property of this treeListLookUpEdit object for example to 5 then you will see "1.2" text in control and node with such text will be focused:
treeListLookUpEdit.EditValue = 5;

WPF Printing FlowDocument not centering

I want to print a page from some text I have with a small header.
I wanted all the text to be centered on the page but I'm not sure how to do it..
Here is my code.. t is of type track which is just an object that holds information like artist name, album name, song title, and lyrics.
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() != true)
{ return; }
FlowDocument doc = new FlowDocument();
Section sec = new Section();
Paragraph header = new Paragraph();
Paragraph body = new Paragraph();
Bold boldSong = new Bold();
boldSong.Inlines.Add(new Run(t.Song));
header.Inlines.Add(boldSong);
header.Inlines.Add(new LineBreak());
Bold boldArtist = new Bold();
if (!string.IsNullOrWhiteSpace(t.Artist))
{
boldArtist.Inlines.Add(new Run(t.Artist));
header.Inlines.Add(boldArtist);
header.Inlines.Add(new LineBreak());
}
Bold boldAlbum = new Bold();
if (!string.IsNullOrWhiteSpace(t.Album))
{
boldAlbum.Inlines.Add(new Run(t.Album));
header.Inlines.Add(boldAlbum);
header.Inlines.Add(new LineBreak());
}
header.TextAlignment = TextAlignment.Center;
body.Inlines.Add(t.iTunesFileTrack.Lyrics);
body.TextAlignment = TextAlignment.Center;
doc.Blocks.Add(header);
doc.Blocks.Add(body);
doc.Name = "FlowDoc";
IDocumentPaginatorSource idpSource = doc;
DocumentPaginator holder = idpSource.DocumentPaginator;
holder.PageSize = new Size(dialog.PrintableAreaWidth,
dialog.PrintableAreaHeight);
dialog.PrintDocument(holder, "Lyrics");
The page prints just fine except for the fact that the whole thing clings to the left of the document when printed... I know there is some property I'm not setting correctly or not setting at all..
increase the size of the ColumnWidth property or just make it '999999'

How can I use NLog's RichTextBox Target in WPF application?

How can I use RichTextBox Target in WPF application?
I don't want to have a separate window with log, I want all log messages to be outputted in richTextBox located in WPF dialog.
I've tried to use WindowsFormsHost with RichTextBox box inside but that does not worked for me: NLog opened separate Windows Form anyway.
A workaround in the mean time is to use the 3 classes available here, then follow this procedure:
Import the 3 files into your project
If not already the case, use Project > Add Reference to add references to the WPF assemblies: WindowsBase, PresentationCore, PresentationFramework.
In WpfRichTextBoxTarget.cs, replace lines 188-203 with:
//this.TargetRichTextBox.Invoke(new DelSendTheMessageToRichTextBox(this.SendTheMessageToRichTextBox), new object[] { logMessage, matchingRule });
if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) {
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => {
SendTheMessageToRichTextBox(logMessage, matchingRule);
}));
}
else {
SendTheMessageToRichTextBox(logMessage, matchingRule);
}
}
private static Color GetColorFromString(string color, Brush defaultColor) {
if (defaultColor == null) return Color.FromRgb(255, 255, 255); // This will set default background colour to white.
if (color == "Empty") {
return (Color)colorConverter.ConvertFrom(defaultColor);
}
return (Color)colorConverter.ConvertFromString(color);
}
In your code, configure the new target like this below example:
I hope it helps, but it definitely does not seem to be a comprehensive implementation...
public void loading() {
var target = new WpfRichTextBoxTarget();
target.Name = "console";
target.Layout = "${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}";
target.ControlName = "rtbConsole"; // Name of the richtextbox control already on your window
target.FormName = "MonitorWindow"; // Name of your window where there is the richtextbox, but it seems it will not really be taken into account, the application mainwindow will be used instead.
target.AutoScroll = true;
target.MaxLines = 100000;
target.UseDefaultRowColoringRules = true;
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "console";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
}
If you define a RichTextBoxTarget in the config file, a new form is automatically created. This is because NLog initializes before your (named) form and control has been created. Even if you haven't got any rules pointing to the target. Perhaps there is a better solution, but I solved it by creating the target programatically:
using NLog;
//[...]
RichTextBoxTarget target = new RichTextBoxTarget();
target.Name = "RichTextBox";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = "textbox1";
target.FormName = "Form1";
target.AutoScroll = true;
target.MaxLines = 10000;
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
new RichTextBoxRowColoringRule(
"level == LogLevel.Trace", // condition
"DarkGray", // font color
"Control", // background color
FontStyle.Regular
)
);
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold));
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

Resources