Using LINQ, how do you get all label controls - linq

I want to get a collection of all label controls that are part of a user control. I have the following code:
var labelControls = from Control ctl in this.Controls
where ctl.GetType() == typeof(Label)
select ctl;
but the result is zero results.
Please assist. Thanks.
Edit
I have also tried the following code without success.
this.Controls
.OfType<Label>()
.Where(ctl => ctl.ID.Contains("myPrefix"))
.ToList()
.ForEach(lbl => lbl.ForeColor = System.Drawing.Color.Black);
Again, without success.

Are you sure that the control whose child controls you are parsing actually directly contains Label controls? I suspect that it is a child of the main control that is hosting the labels, in which case, you need to recursively search through the UI tree to find the labels.
Something like:
public static IEnumerable<Label> DescendantLabels(this Control control)
{
return control.Controls.DescendantLabels();
}
public static IEnumerable<Label> DescendantLabels(this ControlCollection controls)
{
var childControls = controls.OfType<Label>();
foreach (Control control in controls)
{
childControls = childControls.Concat(control.DescendantLabels());
}
return childControls;
}

Controls.OfType<Label>() - thats all
For nested controls
public static class ext
{
public static List<Label> GetLabels(this Control control)
{
var chList = control.Controls.OfType<Label>().ToList();
chList.AddRange(((IEnumerable<Control>)control.Controls)
.SelectMany(c => c.GetLabels()));
return chList;
}
}

var labelControls = this.Controls.OfType<Label>();

Related

ComboBox.Item.add(USB1) switch language----- globalization - VS 2019 WPF

I added ComboBox from MainWindow_OnContentRendered, when I start the program, and how ComboBox.Item will find the resource file to change different language?> .How can I put WPF ComboBox content globalization.Thank you.
hello.
A.
1.
public void MyComboBox()
{
ComboBox.Item.add(USB1)
ComboBox.Item.add(USB2)
ComboBox.Item.add(USB3)
}
2.
MainWindow_OnContentRendered
{
MyComboBox();
}
B.
//ResourceHelper.cs
public static void LoadResource(string ) {
var = (from d in _Resourcelist where d.ToString().Equals() select d).FirstOrDefault();
App.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(langType, UriKind.RelativeOrAbsolute) });
Thread.CurrentThread.CurrentCulture = cultureInfo;
hread.CurrentThread.CurrentUICulture = cultureInfo;}
The question sounds quite simple but is quite difficult to answer. I've just started a new WPF application from scratch, so I thought about the issue of switching to a different language at runtime in general. Of course you have to set CurrentCulture and CurrentUICulture like you do in your example. But what about the controls and their textual content?
My solution is a recursive method that I call with MainWindow.Content as parameter, and then it iterates deeper and deeper through the hierarchy of controls:
private static void ReloadAllText(object root)
{
if (root is TextBlock textBlock1)
{
UpdateBinding(textBlock1, TextBlock.TextProperty);
}
else if (root is ContentControl contentControl)
{
if (contentControl.Content is string)
{
UpdateBinding(contentControl, ContentControl.ContentProperty);
}
else
{
ReloadAllText(contentControl.Content);
}
}
else if (root is Panel panel)
{
foreach (var child in panel.Children)
{
ReloadAllText(child);
}
}
else if (root is ItemsControl itemsControl)
{
for (int cnt = 0, cntMax = VisualTreeHelper.GetChildrenCount(itemsControl); cnt < cntMax; cnt++)
{
if (VisualTreeHelper.GetChild(itemsControl, cnt) is TextBlock textBlock2)
{
ReloadAllText(textBlock2);
}
}
foreach (var item in itemsControl.Items)
{
ReloadAllText(item);
}
}
else if (root is Decorator decorator)
{
ReloadAllText(decorator.Child);
}
else if (root is IRaiseLanguageChanged customItem)
{
customItem.RaiseLanguageChanged();
}
}
The method consists of several branches:
For TextBlock (which is also used by default as the text display element inside other, more complicated controls), the Text property is set to the new value. In my case, I just update the binding. In your case, the new text may have a different source, I don't know your architechture.
For ContentControl (which is any control that has a Content property), it depends: If the content is just a string, I can set it to the new value right away. If it's more complex, then I have to recurse deeper.
For Panel (which is the base class for StackPanel, DockPanel, Grid etc.), I just recurse for each child element.
For ItemsControl (so also for your ComboBox!), I recurse for each item. I added the VisualTree part only because I have a control template for an empty list box consisting of only a TextBox saying "no items". If you bind ItemsSource to an enum type, you must renew the ItemsSourceProperty binding.
For Decorator (e.g. Border), I recurse for its single child.
For custom/self-made controls, I have defined a custom interface IRaiseLanguageChanged, so they must implement a RaiseLanguageChanged() method and handle the language switch themselves. After all, a control itself knows best what to do when the language changes.
This reflects only the set of controls I'm currently using. If you have additional control types, then you have to add respective branches. Please post them here, if you have any good ideas!

set value of radcombobox from another combobox

set value of radcombobox2 from another radcombobox1
radcombobox2 is on asp usercontrol & radcombobox1 is on aspx page.
and value is coming from database on time of binding like this
if (result.IsSuccessful)
{
var rcbRadComboBox = (RadComboBox)RadGrid1.MasterTableView.FindControl("RadComboBox1");
if (comboEditAccessGroup != null)
{
comboEditAccessGroup.DataSource = result.Result;
comboEditAccessGroup.DataTextField = "Title";
comboEditAccessGroup.DataValueField = "JobId";
comboEditAccessGroup.DataBind();
}
}
but the problem is that ,i am not able to change selected index which is selected on radcombobox1
I have used
var selectedindexforjob = Request.QueryString["JobId"];
rcbRadComboBox.SelectedValue = selectedindexforjob;
for achieve goal but got failure nothing happens.
please help me.
Radcombobox1====is on aspx page
Radcombobox2=====is on ascx page
Thanks
Add a property to the user control:
public string ComboSelectedValue
{
get { return RadComboBox2.SelectedValue; }
set { RadComboBox2.SelectedValue = value; }
}
And then you can use this property from the page:
MyUserControl.ComboSelectedValue = RadComboBox1.SelectedValue;

Adding syntax highlighting rules to AvalonEdit programmatically

I'm using AvalonEdit in an app that runs my own custom-built language. I want to put in appropriate syntax highlighting into Avalon Edit. Normally this is done by defining the highlighting rules in an xml file by hand.
However, I don't want the highlighting rules to always be falling out of sync with the language grammar whenever I extend the language. So I'm hoping to use the grammar info that's already contained in my coco/R parser to automatically generate these rules.
So is there a way to programmatically add syntax highlighting rules to Avalon Edit?
Thanks
The below code worked for me at least.
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream s = assembly.GetManifestResourceStream("Your.xshd"))
{
using (XmlTextReader reader = new XmlTextReader(s))
{
//Load default Syntax Highlighting
InternalEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
// Dynamic syntax highlighting for your own purpose
var rules = InternalEditor.SyntaxHighlighting.MainRuleSet.Rules;
_HighlightingRule = new HighlightingRule();
_HighlightingRule.Color = new HighlightingColor()
{
Foreground = new CustomizedBrush(SomeColor)
};
String[] wordList = PseudoGetKeywords(); // Your own logic
String regex = String.Format(#"\b({0})\w*\b", String.Join("|", wordList));
_HighlightingRule.Regex = new Regex(regex);
rules.Add(_HighlightingRule);
}
}
internal sealed class CustomizedBrush : HighlightingBrush
{
private readonly SolidColorBrush brush;
public CustomizedBrush(Color color)
{
brush = CreateFrozenBrush(color);
}
public CustomizedBrush(System.Drawing.Color c)
{
var c2 = System.Windows.Media.Color.FromArgb(c.A, c.R, c.G, c.B);
brush = CreateFrozenBrush(c2);
}
public override Brush GetBrush(ITextRunConstructionContext context)
{
return brush;
}
public override string ToString()
{
return brush.ToString();
}
private static SolidColorBrush CreateFrozenBrush(Color color)
{
SolidColorBrush brush = new SolidColorBrush(color);
brush.Freeze();
return brush;
}
}
You can generate an .xshd file in memory using the object model in ICSharpCode.AvalonEdit.Highlighting.Xshd (XshdSyntaxDefinition etc.).
To convert it into an IHighlightingDefinition, use the HighlightingLoader.Load() method. You can also save it to disk (for debugging purposes) by applying the SaveXshdVisitor.
Alternatively, you could implement IHighlightingDefinition yourself and directly create HighlightingRuleSet instances.

Wicket: How can I rerender the current form without losing existing input?

I have a form with a combobox/drop down to select the user language. If the user changes the language, I'd like to update all the labels but leave the input elements alone.
In jQuery, I'd request a list of label IDs and the new texts via JSON and then use a loop like this:
var texts = {[ {id:'nameLabel', text:'First Name'}, {id:'familyLabel', text:'Family Name'} ]};
for( var i=0; i<texts.length; i++) {
var item = texts[i];
$('#'+item.id).text(item.text);
}
That would update all the labels without modifying anything else. How do I do this in Wicket?
[EDIT] What I tried:
DropDownChoice<Locale> ddc = new DropDownChoice<Locale>(...);
ddc.add( new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
#Override
protected void onUpdate( AjaxRequestTarget target ) {
getSession().setLocale( language );
for( MarkupContainer label : labels ) {
target.addComponent( label );
}
}
});
This does change the labels but it also renders all the input fields again. I found no way to access the current values of the input fields.
[EDIT2] The list of labels is created like so:
StringResourceModel usernameLabel = new StringResourceModel("usernameLabel", this, new Model<ValueMap>(map));
labels.add(add(new Label("usernameLabel", usernameLabel)));
This is wrong:
labels.add(add(new Label("usernameLabel", usernameLabel)));
You're not adding Label instances to 'labels', it's repeatedly adding the container you are adding it to (probably the Page instance). The method 'add()' doesn't return the component being added, it returns the container you are adding the components into.
Try changing it to:
Label label = new Label("usernameLabel", usernameLabel);
add(label);
labels.add(label);

What's problem on linq databinding

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
KeyFieldName="CategoryID">
<SettingsEditing Mode="Inline" />
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True"></EditButton>
<NewButton Visible="True"></NewButton>
<DeleteButton Visible="True"></DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn Caption="CategoryID" FieldName="CategoryID"
VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="CategoryName" FieldName="CategoryName"
VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Description" FieldName="Description"
VisibleIndex="3">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
C# syntax:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { p.CategoryID, p.CategoryName, p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
If you run the code, you get a gridview which is filled by NorthWind Categories table. If you click on command button of grid whose are on left side, you get insert/update field, but you have not access to give input. They are gone to read only mode.
If I replace the above C# syntax with below
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories);
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
then it works fine. Now you can work with command button with out facing any problem.
I want to know what the problem is, why the first syntax does not work. Maybe you say
Anonymous types are class types that consist of one or more public read-only properties. But when you need to join more than one table and need to select several fields not all than what you do. Hope you not say linq is fail to do that or Don't think it is possible. Hope there must be any technique or else something to bind control with Anonymous type. Plz show some syntax .
The problem is that the result set is collection of Anonymous type as you supposed and the grid doesn't know how to treat it. What you have to do is to use RowInserting and RowUpdating events of the grid.
Here is an example of how I use DevExpress grid with NHibernate:
protected void gridAgentGroups_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
var currentAgentGroup = new AgentGroup();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
protected void gridAgentGroups_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
int currentAgentGroupId = (int)((AgentGroup)currentGrid.GetRow(currentGrid.EditingRowVisibleIndex)).Id;
var currentAgentGroup = AgentGroups.Where(ag => ag.Id == currentAgentGroupId).FirstOrDefault();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
I hope this will help.
Just a wild guess - you're binding your data to the grid using field names - yet, your anonymous type doesn't really have any field names.
Does it make any difference if you try this code:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { CategoryID = p.CategoryID,
CategoryName = p.CategoryName,
Description = p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
Again - I don't have the means to test this right now, it's just a gut feeling..... try it - does that help at all??
You actually can bind with anonymous type as you see the already filled rows. But: the grid itself cannot know how you build the query and what to add additionally to the visible columns (if there are valid default values).
As you use Developer Express' grid you have the option to provide your own update / edit form and handle everything needed on your own.

Resources