I am trying to get the selected value from a list box on the Windows Phone 7 platform. The data in my listbox is made up of three columns, consisting of 2 text blocks and 1 image object.
How should i put the code in the way that i can get the text (The data in any of the text block) of the selected one?
Below is my code for defining the grid:
//Define grid column, size
Grid schedule = new Grid();
foreach (var time in timeSplit)
{
timeList = time;
//Column 1 to hold the time of the schedule
ColumnDefinition scheduleTimeColumn = new ColumnDefinition();
GridLength timeGrid = new GridLength(110);
scheduleTimeColumn.Width = timeGrid;
schedule.ColumnDefinitions.Add(scheduleTimeColumn);
//Text block that show the time of the schedule
TextBlock timeTxtBlock = new TextBlock();
timeTxtBlock.Text = time;
//Set the alarm label text block properties - margin, fontsize
timeTxtBlock.FontSize = 28;
timeTxtBlock.Margin = new Thickness(0, 20, 0, 0);
//Set the column that will hold the time of the schedule
Grid.SetColumn(timeTxtBlock, 0);
schedule.Children.Add(timeTxtBlock);
}
foreach (var title in titleSplit)
{
titleList = title;
//Column 2 to hold the title of the schedule
ColumnDefinition scheduleTitleColumn = new ColumnDefinition();
GridLength titleGrid = new GridLength(500);
scheduleTitleColumn.Width = titleGrid;
schedule.ColumnDefinitions.Add(scheduleTitleColumn);
//Text block that show the title of the schedule
TextBlock titleTxtBlock = new TextBlock();
if (title.Length > 10)
{
string strTitle = title.Substring(0, 10) + "....";
titleTxtBlock.Text = strTitle;
}
else
{
titleTxtBlock.Text = title;
}
//Set the alarm label text block properties - margin, fontsize
titleTxtBlock.FontSize = 28;
titleTxtBlock.Margin = new Thickness(60, 20, 0, 0);
//Set the column that will hold the title of the schedule
Grid.SetColumn(titleTxtBlock, 1);
schedule.Children.Add(titleTxtBlock);
//scheduleListBox.Items.Add(schedule);
}
foreach (var category in categorySplit)
{
categoryList = category;
//Column 3 to hold the image category of the schedule
ColumnDefinition categoryImageColumn = new ColumnDefinition();
GridLength catImgnGrid = new GridLength(70);
categoryImageColumn.Width = catImgnGrid;
schedule.ColumnDefinitions.Add(categoryImageColumn);
TextBlock categoryTxtBlock = new TextBlock();
categoryTxtBlock.Text = category;
//set the category image and its properties - margin, width, height, name, background, font size
Image categoryImage = new Image();
categoryImage.Margin = new Thickness(-50, 15, 0, 0);
categoryImage.Width = 50;
categoryImage.Height = 50;
if (category == "Priority")
{
categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/exclamination_mark.png", UriKind.Relative));
}
else
if (category == "Favourite")
{
categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/star_full.png", UriKind.Relative));
}
Grid.SetColumn(categoryImage, 2);
schedule.Children.Add(categoryImage);
}
scheduleListBox.Items.Add(schedule);
}
Code for selected value of listbox:
string selectedName;
private void scheduleListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
//Get the value of selected value in scheduleListBox
if (null != scheduleListBox.SelectedItem)
{
selectedName = (scheduleListBox.SelectedItem as ListBoxItem).Content.ToString();
}
MessageBox.Show("Selected name : " + selectedName);
}
ListBoxItem.Content is the Grid you added to ListBox.Items. Then you can access Grid.Children to get added TextBlocks, resp. their Text properties.
Above is a formal answer. On another note and despite your code containing lots of white spaces, I don't believe that it can work. For example you're adding several images (textblocks) into a single grid cell. Is that intended? I don't think so. Didn't you want to use listbox itm with just one date (is it a date?), one title and one image? If so, change your logic.
ben tan !
you can get Tab of control :
Example:
string a = "abc"
grid myGrid = new grid();
myGrid.Tag = a;
when selectionChange you get Tab in control Grid ?
Related
The grid is already instantiated with the columns at the start of the code outside the foreach loop, within this loop, rows are being instantiated.
foreach (var post in posts)
{
Frame featuredFrame = new Frame();
featuredFrame.Padding = 20;
featuredFrame.Margin = new Thickness(0, 10, 0, 0);
Label postTitle = new Label();
postTitle.FontSize = Device.GetNamedSize(NamedSize.Subtitle, typeof(Label));
BoxView titleSeparator = new BoxView();
titleSeparator.Color = Color.Gray;
titleSeparator.HeightRequest = 1;
titleSeparator.HorizontalOptions = LayoutOptions.Fill;
Image postFeaturedImage = new Image();
postFeaturedImage.Source = ImageSource.FromUri(imageUri);
postFeaturedImage.Aspect = Aspect.AspectFill;
BoxView imageSeparator = new BoxView();
imageSeparator.Color = Color.Gray;
imageSeparator.HeightRequest = 2;
imageSeparator.HorizontalOptions = LayoutOptions.Fill;
Label publishDate = new Label();
publishDate.FontSize = Device.GetNamedSize(NamedSize.Caption, typeof(Label));
StackLayout postDetails = new StackLayout();
postDetails.Children.Add(postTitle);
postDetails.Children.Add(titleSeparator);
postDetails.Children.Add(postFeaturedImage);
postDetails.Children.Add(imageSeparator);
postDetails.Children.Add(publishDate);
postDetails.Margin = new Thickness(0);
postDetails.Padding = new Thickness(0);
featuredFrame.Content = postDetails;
postGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
postGrid.Children.Add(featuredFrame, columnNumber, rowNumber);
}
As you can see, the rows are being created with the height set to Auto, this should mean the rows are the same height as the children.
This is the result of the code above:
This is the result of the code above with postDetails.Children.Add(postFeaturedImage); commented out:
In the screenshot with the images, there is a lot of blank space below the publish date-time text. In the screenshot without the images, this blank space is gone.
I need the pictures visible, but the blank space shouldn't be there. How can I fix this?
I ran into the same issue (that's how I found the question) and I have managed to fix it.
I solved the problem by adding VerticalOptions like this:
postDetails.VerticalOptions = LayoutOptions.Start;
and make sure that you have Height = GridLength.Auto for the RowDefinition.
Currently my images just go down vertically, I want 4 images to display horizontally in each row, I've tried few suggestions on here but can't seem to get it working to work, its quite confusing to me as a beginner.
foreach (MyWCF.dogs c in lc)
{
RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Auto);
g.RowDefinitions.Add(row);
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
BitmapImage image = new BitmapImage();
Image i1 = new Image();
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])p.images);
writer.StoreAsync().GetResults();
}
//var image = new BitmapImage();
image.SetSource(ms);
}
i1.Source = image;
i1.Height = 100;
sp.Children.Add(i1);
Grid.SetRow(sp, gridRef);
g.Children.Add(sp);
gridRef++;
}
(Trying again with the Microsoft code explicitly included. I presume its OK to point to S.O. answers instead of copying an pasting the entirety of the S.O. answer here )
Perhaps the tutorial Grid Class : "Defines a flexible grid area that consists of columns and rows." will help. Then, this S.O. question Adding Image to Grid C# shows how to add images to a WPF grid.
Here is the material from the Grid Class post:
The following C# example demonstrates how to create a grid. In this case, the grid defines three ColumnDefinition elements and four RowDefinition elements that host child content.
// Create the application's main window
mainWindow = new Window();
mainWindow.Title = "Grid Sample";
// Create the Grid
Grid myGrid = new Grid();
myGrid.Width = 250;
myGrid.Height = 100;
myGrid.HorizontalAlignment = HorizontalAlignment.Left;
myGrid.VerticalAlignment = VerticalAlignment.Top;
myGrid.ShowGridLines = true;
// Define the Columns
ColumnDefinition colDef1 = new ColumnDefinition();
ColumnDefinition colDef2 = new ColumnDefinition();
ColumnDefinition colDef3 = new ColumnDefinition();
myGrid.ColumnDefinitions.Add(colDef1);
myGrid.ColumnDefinitions.Add(colDef2);
myGrid.ColumnDefinitions.Add(colDef3);
// Define the Rows
RowDefinition rowDef1 = new RowDefinition();
RowDefinition rowDef2 = new RowDefinition();
RowDefinition rowDef3 = new RowDefinition();
RowDefinition rowDef4 = new RowDefinition();
myGrid.RowDefinitions.Add(rowDef1);
myGrid.RowDefinitions.Add(rowDef2);
myGrid.RowDefinitions.Add(rowDef3);
myGrid.RowDefinitions.Add(rowDef4);
// Add the first text cell to the Grid
TextBlock txt1 = new TextBlock();
txt1.Text = "2005 Products Shipped";
txt1.FontSize = 20;
txt1.FontWeight = FontWeights.Bold;
Grid.SetColumnSpan(txt1, 3);
Grid.SetRow(txt1, 0);
// Add the second text cell to the Grid
TextBlock txt2 = new TextBlock();
txt2.Text = "Quarter 1";
txt2.FontSize = 12;
txt2.FontWeight = FontWeights.Bold;
Grid.SetRow(txt2, 1);
Grid.SetColumn(txt2, 0);
// Add the third text cell to the Grid
TextBlock txt3 = new TextBlock();
txt3.Text = "Quarter 2";
txt3.FontSize = 12;
txt3.FontWeight = FontWeights.Bold;
Grid.SetRow(txt3, 1);
Grid.SetColumn(txt3, 1);
// Add the fourth text cell to the Grid
TextBlock txt4 = new TextBlock();
txt4.Text = "Quarter 3";
txt4.FontSize = 12;
txt4.FontWeight = FontWeights.Bold;
Grid.SetRow(txt4, 1);
Grid.SetColumn(txt4, 2);
// Add the sixth text cell to the Grid
TextBlock txt5 = new TextBlock();
Double db1 = new Double();
db1 = 50000;
txt5.Text = db1.ToString();
Grid.SetRow(txt5, 2);
Grid.SetColumn(txt5, 0);
// Add the seventh text cell to the Grid
TextBlock txt6 = new TextBlock();
Double db2 = new Double();
db2 = 100000;
txt6.Text = db2.ToString();
Grid.SetRow(txt6, 2);
Grid.SetColumn(txt6, 1);
// Add the final text cell to the Grid
TextBlock txt7 = new TextBlock();
Double db3 = new Double();
db3 = 150000;
txt7.Text = db3.ToString();
Grid.SetRow(txt7, 2);
Grid.SetColumn(txt7, 2);
// Total all Data and Span Three Columns
TextBlock txt8 = new TextBlock();
txt8.FontSize = 16;
txt8.FontWeight = FontWeights.Bold;
txt8.Text = "Total Units: " + (db1 + db2 + db3).ToString();
Grid.SetRow(txt8, 3);
Grid.SetColumnSpan(txt8, 3);
// Add the TextBlock elements to the Grid Children collection
myGrid.Children.Add(txt1);
myGrid.Children.Add(txt2);
myGrid.Children.Add(txt3);
myGrid.Children.Add(txt4);
myGrid.Children.Add(txt5);
myGrid.Children.Add(txt6);
myGrid.Children.Add(txt7);
myGrid.Children.Add(txt8);
// Add the Grid as the Content of the Parent Window Object
mainWindow.Content = myGrid;
mainWindow.Show ();
I am trying to make an application which reads out RSS feeds and shows them in an WPF form. To separate the posts I am using a grid and add 2 more RowDefinitions (one for the title and one for the subject).
Currently I am stuck. I want to add some Textblocks to the Rows that I just defined, but I have no idea how because they don't have names. Does anyone have an idea?
What I currently have:
//defining Grid
Grid post = new Grid();
post.HorizontalAlignment = HorizontalAlignment.Left;
post.VerticalAlignment = VerticalAlignment.Top;
post.Margin = new Thickness(10);
post.ShowGridLines = true;
post.ColumnDefinitions.Add(new ColumnDefinition()
{
Width = new GridLength(500)
});
//loop trough all RSS feeds
foreach (SyndicationItem item in feed.Items)
{
//add rows for title and Summary
post.RowDefinitions.Add(new RowDefinition()
{
Height = new GridLength(50),
});
post.RowDefinitions.Add(new RowDefinition()
{
Height = new GridLength(50)
});
//Grid.SetRow(TitleTextblock, 0);
//Grid.SetRow(SummaryTextblock, 1);
//fills textblocks
post.Children.Add(new TextBlock()
{
Text = item.Title.Text
});
post.Children.Add(new TextBlock()
{
Text = item.Summary.Text
});
}
//show grid on window
this.Content = post;
which results in:
this
Allright, it looks like a problem with setting your Definitions correctly:
//defining Grid
Grid post = new Grid();
post.HorizontalAlignment = HorizontalAlignment.Left;
post.VerticalAlignment = VerticalAlignment.Top;
post.Margin = new Thickness(10);
post.ShowGridLines = true;
post.ColumnDefinitions.Add(new ColumnDefinition()
{
Width = new GridLength(500)
});
//add local field to keep track of what row you're on
int rowdeff = 0;
//loop trough all RSS feeds
foreach (SyndicationItem item in feed.Items)
{
//add rows for title and Summary
post.RowDefinitions.Add(new RowDefinition()
{
Height = new GridLength(50),
});
post.RowDefinitions.Add(new RowDefinition()
{
Height = new GridLength(50)
});
//create the textblocks
TextBlock TitleTextblock = new TextBlock;
TextBlock SummaryTextblock = new TextBlock;
//add content to textblocks
TitleTextBlock.Text = item.Title.Text;
SummaryTextblock.Text = item.Summary.Text;
//set definitions
Grid.SetColumn(TitleTextblock, 0);
Grid.SetColumn(SummaryTextblock, 1);
Grid.SetRow(TitleTextblock, rowdeff);
Grid.SetRow(SummaryTextblock, rowdeff);
//fills textblocks
post.Children.Add(TitleTextBlock);
post.Children.Add(SummaryTextblock);
//add next row
rowdeff++;
}
//show grid on window
this.Content = post;
You can try
TextBlock textBlock = new TextBlock();
Grid.SetRow(textBlock, 0);
Grid.SetColumn(textBlock, 0);
Hope this helps you
I am creating small program that has dynamically created combo boxes. Each time the user opens the program, based on some context, there could be 3-30 items that need 4 drop down lists for selection. I am creating these based off of the following code, which is just a snippet.
for (int i = 0; i < 4; i++)
{
s.Children.Add(new ComboBox()
{
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(m, -25, 0, 0),
Width = 75,
Height = 25,
FontSize = 12,
Name = "obj1_" + i.ToString(),
ItemsSource = objs,
});
m = m + 50;
s.Children.Add(new Label()
{
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(m, -25, 0, 0),
Width = 25,
Height = 25,
FontSize = 12,
Name = "lbl1_" + i.ToString(),
});
}
s is a stack panel that I am adding each of the combo boxes too. The ItemSource is from a small method elsewhere to figure out which list should go into the drop down.
My question is, how do I call the events for these created combo boxes? Trying
private void obj1_1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox this_box = (ComboBox)sender;
lbl1_1.Content = "!!!";
}
works well enough but the label doesn't exist in the current context.
Also, am I creating the boxes and labels the best way for this type of scenario?
Thanks in advance.
Inside you for loop
1)Create an new Panel
2)Add the label and combo to that panel
3)Add the newly created panel to s
Inside your obj1_1_SelectionChanged event:
1)Find the Parent control of the ComboBox
2)Search for the label inside its Children and update its text
Solution 2
When you create your controls create a Guid (or an int) and set the Tag property of your controls to that object.
Now when you are on a combo you can search your Window for the label with the same Tag
for (int i = 0; i < 4; i++)
{
Guid g = Guid.NewGuid();
s.Children.Add(new ComboBox()
{
Tag = g
});
s.Children.Add(new Label()
{
Tag = g
});
}
I need to show some data in a structured way with colored letters and rows with background colors.
I made a grid in a WPF Window. It shows the textboxes and some of the labels, but none of the text. Also the column header, last column, gridseperators, grid bot and left edges are invisible.
My grid is called propertiesView.
Code for adding header elements (labels)
private void AddHeaderElement(string text, int row, int col)
{
Label headerElement = new Label();
headerElement.Height = cellHeight;
headerElement.Width = cellWidth;
headerElement.DataContext = text;
headerElement.Background = headerBackground;
headerElement.BorderBrush = new SolidColorBrush(Color.FromRgb(120, 120, 120));
headerElement.BorderThickness = new Thickness(3);
propertiesView.Children.Add(headerElement);
Grid.SetRow(headerElement, row);
Grid.SetColumn(headerElement, col);
}
Code for adding cells
RichTextBox cell = new RichTextBox();
cell.Height = cellHeight;
cell.Width = cellWidth;
cell.ToolTip = toolTip;
cell.DataContext = text;
cell.Background = rowDifferent;
propertiesView.Children.Add(cell);
//box.SetValue(Grid.RowProperty, rowCount);
//box.SetValue(Grid.ColumnProperty, columnCount);
Grid.SetRow(cell, rowCount);
Grid.SetColumn(cell, columnCount);
Code for adding grid seperators
GridSplitter colSeperator = new GridSplitter();
colSeperator.Margin = new Thickness(-2.5, 0, 0, 0);
colSeperator.Width = 5;
colSeperator.ResizeDirection = GridResizeDirection.Columns;
colSeperator.ResizeBehavior = GridResizeBehavior.CurrentAndNext;
colSeperator.VerticalAlignment = VerticalAlignment.Stretch;
colSeperator.HorizontalAlignment = HorizontalAlignment.Left;
propertiesView.Children.Add(colSeperator);
Grid.SetColumn(colSeperator, 0);
Grid.SetRowSpan(colSeperator, totalRows + 1);
The tooltips do show the right text.
I tried using TextBox instead of RichTextBox and setting all this stuff in the class constructor instead of a seperate method.
Well it seems like you just never set the Content dependency property on your labels, or the Document of your RichTextBoxes.
For your labels, as you set the text parameter as the DataContext, you can just add something like
headerElement.SetBinding(Label.ContentProperty, new Binding());
Turns out I needed labels with textblocks, spans and runs.
Style can be added on the span (through properties like Foreground, TextDecoration or FontWeight). Add the text to the span inside a Run, then add all spans to a textblock, which is shown through a label.
Span span = new Span();
span.Foreground = Brushes.Black;
span.Inlines.Add(new Run("Text"));
textBlock.Inlines.Add(span);
Label cell = new Label();
cell.MinHeight = cellHeight;
cell.MaxWidth = cellWidth * 3;
cell.MinWidth = cellWidth;
cell.ToolTip = "toolTip";
cell.BorderThickness = new Thickness(2);
TextBlock cellText = new TextBlock();
cellText.HorizontalAlignment = HorizontalAlignment.Stretch;
cellText.TextWrapping = TextWrapping.WrapWithOverflow;
cell.Content = cellText;
The text works now, I should be able to get the gridseperators working.