Find child elements in a WPF ListView ItemTemplate - c#

Given a populated ListView, how do I iterate through each bound template and pluck out the contained ComboBox (or any other control contained in DataTemplate)?
<ListView x:Name="lstCommands">
<ListView.ItemTemplate>
<DataTemplate>
<Grid x:Name="gridInputs">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding Path=Key}"/>
<ComboBox x:Name="cbInputCmd" Grid.Column="1" ItemsSource="{Binding Source={StaticResource inputData}}" Tag="{Binding Path=Key}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>

Firstly, avoid doing so unless you really need to. If you absolutely must, you can use DataTemplate.FindName, where the templated parent is the ListViewItem generated by the ListView. To get the ListViewItem, use the ListView's ItemContainerGenerator.
Update: the reason I suggest avoiding this approach wherever possible is because it creates more tightly-coupled, brittle code. The OP didn't mention why he wanted to do what he was asking, but I suspect he could achieve his goal by more idiomatic means, such as with bindings.

is simple
just do this
<ListViewItem Name="mainiterm" Style="{ StaticResource inboxlst}" Selected="ListViewItem_Selected_1">
<Canvas Style="{StaticResource inboxcanvas}">
<Label Name="namelabel" Content="lalallala1" Style="{StaticResource inboxlabel1}" />
<Label Content="lalallala" Style="{StaticResource inboxlabel2}"/>
</Canvas>
</ListViewItem>
and vb
Dim r = mlistview.Items.GetItemAt(i)
Dim textYear As Label = Nothing
Dim s As Canvas = r.Content
Dim a As Label = s.Children.Item(1)
a.Content = "Disconnected"
a is a label, s is a cavas

you could try using the LogicalTreeHelper or VisualTreeHelper which lets you query an object for its children, but if you were binding your combo boxes to the item your list view is displaying you would not have to worry about 'getting' them at all.
Then you could just look at your item.
Any time you find yourself walking the visual or logical tree looking for elements which exist in your ui, so that you can get their values, ask yourself 'what am i missing here' 'why isnt my business (or view model) being updated with relevant data when the user interacts with the ui?'
For the example above I would build a view model that had two properties, a String (for your label) and a SelectedItem (that you could bind your combo box selected item to). its easier, more robust and it stops you having to trawl through the visual elements. one of the beautiful things about xaml/wpf is that it seperates your logic from your view. what you are suggesting will break this model. You will entangle the view with your logic and from there on it gets messy...

Related

Set LongListSelector

I'm developing a Windows Phone app to practice my knowledge within the control LongListSelector. One of the pages in the app, the middle one has this code:
<!--Panorama item two-->
<phone:PanoramaItem x:Name="tasksPage" Header="Tasks">
<!--Double line list with image placeholder and text wrapping using a floating header that scrolls with the content-->
<phone:LongListSelector Margin="0,-38,-22,2" ItemsSource="{Binding Items}" LayoutMode="List">
<phone:LongListSelector.ListHeaderTemplate>
<DataTemplate>
<Grid Margin="12,0,0,38">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="second item"
Style="{StaticResource PanoramaItemHeaderTextStyle}"
Grid.Row="0"/>
</Grid>
</DataTemplate>
</phone:LongListSelector.ListHeaderTemplate>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="12,2,0,4" Height="105" Width="432">
<!--Replace rectangle with image-->
<Border BorderThickness="1" Width="99" Height="99" BorderBrush="#FFFFC700" Background="#FFFFC700"/>
<StackPanel Width="311" Margin="8,-7,0,0">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Margin="10,0" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeLarge}" />
<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="10,-2,10,0" Style="{StaticResource PhoneTextSubtleStyle}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
Could someone please explain briefly what the DataBindings is and how to use them (I have done some research). Could I for instance bind the LongListSelector to a list in IsolatedStorage?
I have create a ListBox before in another app, loading content from IsolatedStorage into it, but I don't know if this is the right approach. Right now the items in the LongListSelector has a yellow image right left to it - can i do the same if I'm loading the content programatically from IsolatedStorage?
I know this might be a couple or three questions, but I think they're fairly simple to answer for someone experienced.
Thanks!
Your LongListSelector has a number of items inside. They are added there through data binding by binding the ItemsSource to items which are a part of Items collection. This collection can be a List<T> or more often ObservableCollection<T> because that way, if properly implemented, the changes in ObservableCollection will reflect in your LongListSelector. The T is the type of your item - for example, a class called Book. This collection needs to be defined as a part of the DataContext object, which you set on the whole page or a part of page.
Now, as I mentioned, the Items collection is probably full of items - objects defined to have certain properties. In your case, those properties are LineOne and LineTwo, which are probably strings.
You cannot directly bind to items in isolated storage. You first need to load those items into memory. Let's assume you have a list of items serialized to JSON or XML format in your isolated storage, which is one popular way of keeping the list in isolated storage. You need to load them into a collection (deserialize) and then bind to LongListSelector. It is the right approach, yes.
The yellow image/rectangle/border defined on the left is static, but it can be there, of course. It will simply be rendered there as a part of every item you have in your LongListSelector and it will not depend on the object which you bind to.
I suggest you read the following articles/questions and answers which may explain the concept of binding to a list easier for you to understand:
MSDN - Quickstart: Data binding to controls for Windows Phone
Stack Overflow - WP8 working with XML and LongListSelector
GeekChamp - The New LongListSelector control in Windows Phone 8 SDK
in depth
Simplest explanation (overlysimplified!) is that data binding is binding a property of an object to another property a control above, there's:
<TextBlock Text="{Binding LineOne}" ... />
That is functionally equivalent to something like this:
TextBlock t = new TextBlock();
SomeObject o = new SomeObject() { LineOne = "The value of line 1" };
t.Text = o.LineOne;
// and then a propertychange listener to update t.text if o.lineone ever changes
o.PropertyChanged += (s,e) => { if (e.PropertyName == 'LineOne') t.Text = o.LineOne; };
You can't bind directly to something in isolated storage, but you can have an object load its content from isolated storage, expose those items through an Items property and then set that as the data context of the LLS.
In cases like LongListSelector (or other ItemsControl types) the itemscontrol's ItemsSource property is bound to some collection of objects (like an ObservableCollection<T>, which makes its items update whenever the collection updates. And then a template inside the ItemsControl has bindings to the properties of the individual items in the collection.

Use of DataTemplate

I'm quite new to C# and Windows Phone 7 for that sake, but none the less, I've thrown myself into trying to make a small app for myself. Here's my problem:
I'm trying to set up a DataTemplate that will position my Name and Drinks variables that I've declared in MainPage.xaml.cs. Here's my action when button1 is clicked:
private void button1_Click(object sender, RoutedEventArgs e)
{
string Name = participantName.Text;
int Drinks = 0;
listBox1.Items.Add(Name + Drinks);
}
And here is my DataTemplate from MainPage.xaml
<ListBox Height="Auto" HorizontalAlignment="Stretch" Margin="7,74,0,0" Name="listBox1" VerticalAlignment="Stretch" Width="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<TextBlock Text="{Binding Path=Name}" FontSize="35" />
<StackPanel Width="370">
<TextBlock Text="{Binding Path=Drinks}" FontSize="35" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The problem is that my data is not shown. It works perfectly without the DataTemplate, but as soon as I use it, my text simply doesn't get through. Your help is very much appreciated.
The template itself is ok. The bindings on the template, though, are currently incorrect.
When you add a new item to the list box, you are just adding a plain old string (which is currently missing a space, BTW.) Your bindings, though, expect the object in the list to have a Name property and a Drinks property, which of course the string class does not have.
The usual solution here is to logically separate your data model from your presentation, by creating a class to store the data itself (probably PersonDrink, with the appropriate Name and Drinks properties) and then adding those objects to the list.
You should read up on the MVVM pattern, as it provides an excellent way to ensure that changes in your data are reflected in your view, and visa versa.
http://amarchandra.wordpress.com/2011/12/18/binding-multiple-object-in-wp7-using-listbox/
Here is a sample for binding data using a datatemplate. I hope this might help you.

Populate WPF DataGrid dynamically

My program needs to take input from a fire alarm panel over a serial connection and populate a list based on it. When a new device is reported from the panel, the statement is parsed and the device is added to the device List.
That part of my program all works fine and dandy. The problem now is displaying the list of fire alarm devices to the user.
I am hoping to do this using a DataGrid (unless there's a better way?) but am not able to find a lot of helpful documentation on WPF DataGrids that is relevant to me. Most of what's out there seems to be displaying data from a database. Mine however, needs to update every time the panel spits out a new device description and the device List in my program is appended.
I see I can set AutoGenerateColumns to true and initially display my list just fine. BUT, I would like to customize the column headers. Also this doesn't update when the List is appended so I'm not sure how to "refresh" it.
When AutoGenerateColumns is false, I get no data displayed. When the program runs it shows me the correct number of rows corresponding to the number of items in my list, but no data. Wondering how/if I need to link each column with its corresponding device data member?
Lastly, how do you format a DataGrid to look pretty through re-sizes? I can set column width and all that, but what I want is a few of the columns to be fixed width, and the middle column to expand to fill remaining available area.
This is my first stab at WPF. Any help would be greatly appreciated!
Personaly i dont like DataGrid much. Yes they are easier to bind and they offer built-in resize and sorting options but they are not as flexible as an ItemsControl with a good DataTemplating on your Objects. Let me explain myself.
I tend to populate my ItemsControl with an ObservableCollection. Then, i use a DataTemplate in order to tell my ItemsControl how to display my custom items.
Your CustomObjects can be Modeles objects if your doing MVVM.
If your list is binded to an ObservableCollection, the Added and Removed items will appear dynamicly into your list, which is what i belive your trying to do.
For the column size, you could put a Grid specifying GridColumns width to fixed Width for some columns and * for others so they fill the remaining space.
Here's an alternative to the GridView
I use a ScrollViewer around my ItemControl so if the ItemsControl get too big, you can scroll it.
The ItemsControl's ItemSource is binded to your FireAlarms's ObservableCollection.
The WrapPanel in the ItemsControl will contain each DataTemplate. It's Width is binded to his parent (or ancestor if you will) which is an ItemsControl
<ScrollViewer
Grid.Row="x"
Grid.Column="y"
VerticalScrollBarVisibility="Auto"
Margin="5">
<ItemsControl
BorderBrush="DarkBlue"
BorderThickness="2"
ItemsSource="{Binding Path=FireAlarms}"
ItemTemplate="{StaticResource FireAlarmsTemplate}"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel
Orientation="Horizontal"
Width="{Binding RelativeSource=
{RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}},
Path=ActualWidth}"
>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
Ok then you need a DataTemplate. You can put the DataTemplate in your windows's ressource or in a DataDictionnary. Lets say you have a class :
FireAlarm
{
Public String AlarmInfo1;
Public String AlarmInfo2;
Public String AlarmInfo3;
}
Here could be a nice DataTemplate to start with :
<DataTemplate x:Key="FireAlarms">
<Border
BorderBrush="SteelBlue"
Background="LightBlue"
BorderThickness="2"
Margin="10"
Padding="10">
<StackPanel
Orientation="Vertical"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label
Grid.ColumnSpan="3"
Grid.Row="0"
Content="{Binding Path=AlarmName}"
Margin="5,-5,5,10"
FontWeight="Bold"
FontSize="16"
HorizontalContentAlignment="Center"
HorizontalAlignment="Center">
</Label>
<TextBlock
Text="Alarm information 1" Grid.Row="1" Grid.Column="0" />
<TextBox
Text="{Binding Path=AlarmInfo1}"
Grid.Column="2"
Grid.Row="1"
>
</TextBox>
<TextBlock
Text="Alarm information 2" Grid.Row="2" Grid.Column="0" />
<TextBox
Text="{Binding Path=AlarmInfo2}"
Grid.Column="2"
Grid.Row="2"
>
</TextBox>
<TextBlock
Text="Alarm information 3" Grid.Row="3" Grid.Column="0" />
<TextBox
Text="{Binding Path=AlarmInfo3}"
Grid.Column="2"
Grid.Row="3"
>
</TextBox>
</Grid>
</StackPanel>
</Border>
</DataTemplate>
Ok I hope this is usefull for you. My Template will generate 1 square per alarm. If you'd rather have it in a Table like a GridView, you could modify this using a verticaly oriented stack panel and use a grid with variable // invariable column width but since you asked for anything usefull, i tough i'd guive you something fun to work with!
Enjoy!
Some time back I wrote a post Create DataGrid in WPF using code take a look at it, it will help you in creating data grid in dynamic scenarios like yours
If you a dynamic grid (meaning the number and design of the columns are unknown at design time), I do it with code-behind with binding. I generally use the MVVM pattern (if you not familiar with this, I really recommend reading into it since it is THE pattern when working with WPF).
1) You have to set Auto-Generate columns to false of course and give grid a name (here myDataGrid)
GridViewDataColumn newColumn= new GridViewDataColumn();
myDataGrid.Columns.Add(newColumn)
This will add the column to your grid. Now the column will be empty. Now it depends on your data how to fill it with data. If you bind to a known property on the items, do:
newColumn.Binding = new Binding("knownPropertyName");
In most cases though, you do not know the propertyname and bind to an element in the collection.
Then it would like more:
myDoubleCollection.Add(someDoubleValue); //do this for each item in the itemssource of the grid
int index=myDoubleCollection.Count-1;
newColumn.Binding = new Binding(string.Format("myDoubleCollection[{0}]",index));
So this works also.
Another thing to keep in mind is the deletion of columns. This requires some extra work.
That's a lot of questions rolled into one! I suggest you do a bit more background research before asking questions. I would recommend that your read this codeproject article I wrote about the WPF DataGrid a while back:
http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx
It will answer most of your questions for you!
Take a look at the MVVM pattern, it'll be a huge help as you create this application.
What you want is an ObservableCollection in the ViewModel. You'll bind the ItemsSource property of the datagrid to this collection. Then have your columns bind to various properties on to display them. Whenever this ObservableCollection has an item appended, your front end should update automatically.
To have a column autosize, set the Width="*".
Here's a sample of a datagrid with MVVM
<DataGrid ItemsSource="{Binding FireAlarmCollection}" SelectedItem="{Binding SelectedFireAlarm, Mode=TwoWay}" AutoGenerateColumns="True" CanUserSortColumns="True" HorizontalScrollBarVisibility="Visible" CanUserResizeColumns="True">
</DataGrid>
As you continue your effort, post separate questions for each issue.

Multi-Column Selector

I am searching for some hybrid of ComboBox and ListView and I am wondering why there exists nothing like that, although I feel it's a quite natural wish to have it.
In more detail:
A WPF ItemsControl should have an ItemsSource of all applicable items.
These items have multiple properties, say ID:int, Name:string and Description:string.
Now my ItemControl should:
Show these three properties as nicely aligned columns in some combobox-like drop-down
Provide some way of quickly finding an item by just typing text into a single textbox (without specifying, which property shall be searched). This should either select the first match or filter the items hiding all non-matching ones.
Key is that the control is perfectly usable without a mouse, but also provides some "explorer"-mode, if the user does not remember the perfectly identifying ID but only parts of some description or name.
A configurable "Search-Function" would be nice, and it would be no problem if you would need to explicitly state all the properties to be included in a search or display function.
There is no such control so far, but you can certainly make one easily,
Create a C# Custom Control and define control template as Expander containing a DataGrid/ListView.
You can define dependency properties of your custom control as needed for ListView and do templatebinding for them. Expander's header should be bound to selected item's text or some sort of text representation of your objects.
Alternative:
Add a GRID inside Item Template and define its column definitions. And you can specify multi column values in the GRID easily.
<ComboBox>
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding CustomerName}"/>
<TextBlock Grid.Column="1" Text="{Binding CustomerEmail}"/>
<TextBlock Grid.Column="2" Text="{Binding CustomerPhone}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
By applying widths correctly, and giving margins to textblock, you can create multicolumn list to be displayed easily. Dont forget to TextSearch.SearchPath property in order to be able to select item by keyboad.

Control which field is displayed in the textbox part of a databound WPF ComboBox

I have a ComboBox in WPF which is databound, and has data template which controls how each of the items is displayed. I have made it so that each item is displayed with two bits of text (for the Name and Path properties) and one image (for the Icon property).
At the moment when I select an item from the ComboBox the textbox bit of the ComboBox just changes to say "TestWPF.Result" which is the name of the class which I have populated the ComboBox with.
I'm interested in one (or both) of two things:
How do I change it so that it displays the value of one of the fields there (eg. so it shows the value of the Name field rather than the name of the class)?
Is it possible get it to use the same DataTemplate there as in the list of items, so that once I have selected an item it displays in the closed ComboBox the same way as it looks in the list of items. Basically I've got a DataTemplate called ShowResults and a ComboBox which uses that template. I've also added in a separate ContentControl which I've got to show the details of the selected item in the ComboBox, but I want to get that to replace the textbox in the ComboBox.
Update:
Thanks for the first answer. I've tried using a separate ContentControl, as you've described, and it works fine. The question now is how to replace the textbox part of the ComboBox with this ContentControl. Any hints on that would be most welcome.
Also, is it possible to replace the textbox bit of the ComboBox control with a mixture of the ContentControl and a textbox, so that I can still type in the textbox to help select items from the ComboBox, but then when I close the dropdown the rest ContentControl bit will be populated with the rest of the text and the icon. Hope that makes sense - ask questions if it doesn't!
Code:
I've been asked to post my code - so here it is. I've tried to remove things that I know are definitely not relevant, but I'm not sure exactly what is relevant so when in doubt I've left things in.
<Window x:Class="TestWPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:TestWPF"
Title="Window1" Height="300" Width="843" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="ShowResult" DataType="TestWPF.Result">
<StackPanel Margin="5" Orientation="Horizontal">
<Image Width="32" Height="32" Source="{Binding Path=Image}"/>
<StackPanel Margin="5">
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}"/>
<TextBlock Text="{Binding Path=Path}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid Width="786">
<Button Height="23" HorizontalAlignment="Right" Margin="0,24,166,0" Name="btnTest" VerticalAlignment="Top" Width="75" Click="btnTest_Click">Add</Button>
<ComboBox StaysOpenOnEdit="True" DropDownClosed="comboBox1_DropDownClosed" PreviewTextInput="comboBox1_PreviewTextInput" SelectionChanged="comboBox1_SelectionChanged" ItemTemplate="{StaticResource ShowResult}" Margin="259,109,22,89" Name="comboBox1" IsEditable="True" />
<ContentControl Height="50" Margin="268,0,22,21" Name="contentControl1" VerticalAlignment="Bottom" Content="{Binding ElementName=comboBox1,Path=SelectedValue}" ContentTemplate="{StaticResource ShowResult}"/>
</Grid>
You got the binding part right - binding to the data and using a DataTemplate to display the source the way you want to.
As to your second question, a way to do it would be to use a ComboBox with IsEditable="True" as you have, and withing the TextChanged event handler check if the comboBox.Items contains the new value, if not check use Linq to seach for a match:
if (comboBox.Items.Contains(e.NewValue))
return;
var matches =
with comboBox.Items
select item
where item.BeginsWith(e.NewValue);
if (matches.Count > 0)
comboBox.SelectedItem = matches.First();
Just place the Property Binding expression to the textBox,You dont need to apply template.
Another way to get exact Data template, Place a ContentControl in the place of textBox and assign the same DataTemplate (say x:Name="robinTemplate")
<ContentControl Content="{Binding ElementName=cmbBox,Path=SelectedValue}" ContentTemplate="{StaticResource robinTemplate}"/>
For making the Selected content display in the same way :
Create a copy of the combobox control template and you will find a ContentPresenter there. Replace that with the ContentControl.. This is not the right solution though.

Categories