I'm having problems finding a control (ToggleSwitch) inside my ListView. I have tried several approaches found here on SO or on other places around the web but none seems to be working.
Here is a the listView markup
<ListView Name="LampsListView" ItemsSource="{x:Bind Lamps}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Lamp">
<StackPanel Name="StackPanel">
<TextBlock Margin="10,0" Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Left" />
<ToggleSwitch Margin="10,0" HorizontalAlignment="Right" Name="LampToggleSwitch" IsOn="{x:Bind State, Converter={ StaticResource IntToIsOn}}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I have tried the ContainerFromItem but x will always be null.
foreach (var item in this.LampsListView.Items)
{
var x = this.LampsListView.ContainerFromItem(item);
}
And also the GetChildren approach but even thought GetChildren returns items it wont give me anything I can work with.
private void FindMyStuff()
{
var ch = this.GetChildren(this.LampsListView);
}
private List<FrameworkElement> GetChildren(DependencyObject parent)
{
List<FrameworkElement> controls = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement)
{
controls.Add(child as FrameworkElement);
}
controls.AddRange(this.GetChildren(child));
}
return controls;
}
And I've tried booth finding the StackPanel and go straight for the LampToggleSwitch.
The FindMyStuff() is called right after i've updated the ObservableCollection that is bound to the ListView and the update is done from a this.Dispatcher.RunAsync(). I don't know if this has anything to do with it thought.
Could someone please tell me what I'm doing wrong?
Generally traversing visual tree or getting items by names/types is in most cases a wrong way of doing thigs, much better would be to implement apropriate binding.
Nevertheless if you want to do this, you are almost there. As I've tried it should work like this:
var listViewItem = this.mylist.ContainerFromItem(mylist.Items.First()) as ListViewItem;
var itemsStackPanel = listViewItem.ContentTemplateRoot as StackPanel;
var myToggleSwitch = itemsStackPanel.Children.FirstOrDefault(x => x is ToggleSwitch);
// other way with your helper
var childByHelper = GetChildren(listViewItem).FirstOrDefault(x => x is ToggleSwitch);
Just watch out when you run this, if it's done before list is populated, listVieItems will be null.
Related
I want to be able to say:
Get the first textblock, then the first checkbox, both with the number 1 in their name.
Then if the checkbox is checked, then the textblock can be populated.
See code:
for (int i = 1; i < 10; i++)
{
TextBlock a = (this.FindName(string.Format("tb_{0}", i)) as TextBlock);
CheckBox b = (this.FindName(string.Format("ck_{0}", i)) as CheckBox);
if (b.IsChecked.HasValue)
{
if (a != null) a.Text = data.ArrayOfSensors[i].ToString();
}
else
{
if (a != null) a.Text = data.ArrayOfSensors[0].ToString();
}
}
So when the checkbox is enabled, the textblock will be populated with the index from the array.
Many thanks!
EDIT: A slightly better explanation:
The textblocks are named: tb_1, tb_2 etc
The Checkboxes are named: cb_1, cb_2 etc
The array is:
[0] 0
[1] 100
[2] 150
The number is what they all have in common. So I can use a for loop with i as a common variable for each. I also have about 50 textboxes and Comboboxes and don't want to write each one out individually.
EDIT: My ComboBoxes and Textblocks are created on Xaml code like this:
<CheckBox x:Name="Cb_1" Width="15" Height="15" Margin="349,53,127,164" IsChecked="True" />
<TextBlock x:Name="tb_1" Text="80" Height="20" Width="20" Margin="266,35,205,177" />
Its hard to answer without seeing what your XAML looks like, however it sounds like you may be trying to use WPF like it is WinFirms.
To build an interface like this in WPF, you should start by creating a custom class to hold your data, and then use an ItemsControl to render your collection of data.
For example, your class might look something like this
public class SensorData() : INotifyPropertyChanged
{
// should implement INotifyPropertyChanged of course
public string Text { get; set; }
public bool IsChecked { get; set; }
}
And an ObservableCollection<SensorData> might be rendered using an <ItemsControl> with a ItemsPanelTemplate containing both a CheckBox and a TextBox
<ItemsControl ItemsSource="{Binding MyCollectionOfSensorData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Checked="{Binding IsChecked}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
This will loop through the collection of SensorData objects, and render a CheckBox and TextBox for each one. If you want to do any manipulation of the data from the code-behind, you only need to modify the properties of the SensorData objects.
For example, you could have a loop that goes
for (int i = 0; i < MyCollectionOfSensorData.Length; i++)
{
SensorData item = MyCollectionOfSensorData[i];
if (item.IsChecked)
item.Text = data.ArrayOfSensors[i].ToString();
else
item.Text = "0";
}
And there would be no interaction with the UI objects at all.
I have a ListBox in xaml which has a sub-ListBox inside the top-level ListBox's item template. Because the sub-ListBox is multi-select, and I can't bind the SelectedItems of the sub-ListBox to a viewmodel property for some reason, I'm trying to do a lot of this in the view code-behind.
I have everything working, except for one snag: I want to select all items in each sub-ListBox by default. Since the SelectedItems aren't data-bound, I'm trying to do it manually in code whenever a SelectionChanged event fires on the top-level ListBox. The problem is that I don't know how to get from the top-level ListBox to the sub-ListBox of the top-level selected item. I think I need to use the visual tree, but I don't know how to even get the dependency object that corresponds to the selected item.
Here's the code:
<ListBox ItemsSource="{Binding Path=Stuff}" SelectionChanged="StuffListBox_SelectionChanged" SelectedItem="{Binding Path=SelectedStuff, Mode=TwoWay}" telerik:RadDockPanel.Dock="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<telerik:RadDockPanel>
<TextBlock Text="{Binding Path=Name}" telerik:RadDockPanel.Dock="Top" />
<ListBox ItemsSource="{Binding Path=SubStuff}" SelectionMode="Multiple" SelectionChanged="SubStuffListBox_SelectionChanged" Visibility="{Binding Converter={StaticResource StuffToSubStuffVisibilityConverter}}" telerik:RadDockPanel.Dock="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</telerik:RadDockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The converter ensures that only the selected top-level item has a visible sub-ListBox, and that's working.
I need to implement the following method:
private void StuffListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox stuffListBox = (ListBox)sender;
foreach (Stuff stuff in e.AddedItems)
{
...
subStuffListBox.SelectAll();
}
}
I tried doing stuffListBox.ItemContainerGenerator.ContainerFromItem(stuff), but that always returns null. Even stuffListBox.ItemContainerGenerator.ContainerFromIndex(0) always returns null.
I also get strange behaviour from the selection changed method. 'e.AddedItems will contain items, but stuffListBox.SelectedItem is always null. Am I missing something?
From what I've read, my problem is coming from the fact that the containers haven't been generated at the time that I'm getting a selection change event. I've seen workarounds that involve listening for a the item container generator's status changed event, but I'm working in Silverlight and don't have access to that event. Is what I'm doing just not possible in Silverlight due to the oversight of making SelectedItems on a ListBox read-only?
Like you say this is probably best done in the ViewModel but you can select all the sub list items in code behind using VisualTreeHelper.
private void StuffListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var stuffListBox = (ListBox)sender;
ListBoxItem item = (ListBoxItem)stuffListBox.ContainerFromItem(stuffListBox.SelectedItem);
ListBox sublist = FindVisualChild<ListBox>(item);
sublist.SelectAll();
}
FindVisualChild Method as per MSDN
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
I'm building a Windows Store App using the OOTB Grid App template. I'm noticing that there is a 500-1000 millisecond pause when I am navigating from page to page either forward or backward. It is mainly noticeable when I hit the back button (the back arrow stays in the "Hit" state for the 500-1000 ms). Going forward isn't as bad because usually the screen has animations and transitions to fill most of the loading times.
My first thought was that there was something on in the LoadState method that was causing the slowdown, but the only thing I have that isn't from the template I'm running on a background thread and calling it with an async preface.
My second thought was that I was passing a complex object to each page's navigationParameter instead of just passing a simple string. I didn't think this could be the cause since the object should be pass by reference so there really shouldn't be any slowdown because I passed a non-string into the NavigateTo method.
(I haven't read any guidance about this, so I don't know if the page navigation is less snappy when passing non-strings between pages. If anyone has any insight into this, that would be wonderful)
My next thought was that my Xaml is too complex and the pause is the Xaml loading all of the items into the list and what not. This might be the issue and if so, I have no idea how to test or fix it. The UI feels fluid once everything is loaded (all of the items on the page scroll without stutter)
If this is the case, is there any way to show a loading circle with the Xaml generates and then once it is done generating, fade the content in and the circle out?
The main thing that I want to fix is I don't want the back button to "freeze" in the Hit. Any help or guidance would be great!
Basic app info:
Pages have combinations of List and Grid View controls with different Item templates. No images or graphics are used, but I do use a gradient brush on some of the item templates (not super complex, similar to the start screen item gradients). Most lists only have 20-30 items, some more most less.
The average page has 1 Item Source, and 2 Item Display controls, a list and a scroll viewer that holds the details of the selected item.
Details for any item are about 2-3 normal paragraphs of details text and 3-4 < 20 char strings.
EDIT: Project Code:
Page 1 code
protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
if (navigationParameter == null)
this.DefaultViewModel["Groups"] = GlobalData.Catalog.Catalog;
else
this.DefaultViewModel["Groups"] = navigationParameter;
await GlobalData.LibraryDownload.DiscoverActiveDownloadsAsync();
}
The DiscoverActiveDownloadsAsync method is the same code from this example code
SaveState, OnNavigateTo, and OnNavigateFrom methods haven't been modified from the LayoutAwarePage base class.
Page 2 code
protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
if (navigationParameter is CatalogBook)
{
var catBook = (CatalogBook)navigationParameter;
var book = catBook.Book;
await book.InitializeAsync();
this.DefaultViewModel["Group"] = catBook;
this.DefaultViewModel["Items"] = book.Items;
}
else if (navigationParameter is IBook)
{
var book = await Task.Run<IBook>(async () =>
{
var b = (IBook)navigationParameter;
await b.InitializeAsync();
return b;
});
this.DefaultViewModel["Group"] = book;
this.DefaultViewModel["Items"] = book.Chapters;
}
if (pageState == null)
{
// When this is a new page, select the first item automatically unless logical page
// navigation is being used (see the logical page navigation #region below.)
if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null)
{
this.itemsViewSource.View.MoveCurrentToFirst();
}
}
else
{
// Restore the previously saved state associated with this page
if (pageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null)
{
var number = 0;
if(!int.TryParse(pageState["SelectedItem"].ToString(), out number)) return;
var item = itemsViewSource.View.FirstOrDefault(i => i is ICanon && ((ICanon)i).Number == number);
if (item == null) return;
this.itemsViewSource.View.MoveCurrentTo(item);
itemListView.UpdateLayout();
itemListView.ScrollIntoView(item);
}
}
}
...
protected override void SaveState(Dictionary<String, Object> pageState)
{
if (this.itemsViewSource.View != null)
{
var selectedItem = this.itemsViewSource.View.CurrentItem;
pageState["SelectedItem"] = ((ICanon)selectedItem).Number;
}
}
The InitializeAsync method reads from an SQLite database some of the basic information about a book (chapters, author, etc.) and generally runs very quickly (< 10ms)
Grid code
I get the data by querying an SQLite database using the SQLite-net Nuget Package's async methods. The queries usually look something like this:
public async Task InitializeAsync()
{
var chapters = await _db.DbContext.Table<ChapterDb>().Where(c => c.BookId == Id).OrderBy(c => c.Number).ToListAsync();
Chapters = chapters
.Select(c => new Chapter(_db, c))
.ToArray();
HeaderText = string.Empty;
}
I populate the grids by using the following Xaml:
<CollectionViewSource
x:Name="groupedItemsViewSource"
Source="{Binding Groups}"
IsSourceGrouped="true"
ItemsPath="Items"
d:Source="{Binding DisplayCatalog, Source={d:DesignInstance Type=data:DataCatalog, IsDesignTimeCreatable=True}}"/>
<common:CatalogItemTemplateSelector x:Key="CatalogItemTemplateSelector" />
...
<GridView
Background="{StaticResource ApplicationPageLightBackgroundThemeBrushGradient}"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
SelectionMode="Multiple"
Grid.Row="1"
ItemTemplateSelector="{StaticResource CatalogItemTemplateSelector}"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick" Margin="-40,0,0,0">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Height="628" Margin="120,10,0,0" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="1,10,0,6">
<Button
AutomationProperties.Name="Group Title"
Click="Header_Click"
Style="{StaticResource TextPrimaryButtonStyle}" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Margin="0,0,80,0" ItemHeight="{StaticResource ItemHeight}" ItemWidth="{StaticResource ItemWidth}"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
</GridView>
the CatalogItemTemplateSelector class looks like this:
public class CatalogItemTemplateSelector : DataTemplateSelector
{
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
// cast item to your custom item class
var customItem = item as ICatalogItem;
if (customItem == null)
return null;
string templateName = String.Empty;
if (customItem is CatalogFolder || customItem is CatalogMoreFolder)
{
templateName = "FolderItemDataTemplate";
}
else if (customItem is CatalogBook || customItem is CatalogMoreBook)
{
templateName = "BookItemDataTemplate";
}
object template = null;
// find template in App.xaml
Application.Current.Resources.TryGetValue(templateName, out template);
return template as DataTemplate;
}
}
Both of the templates are ~20 lines of Xaml, nothing special
If there are other pieces of code that I haven't included, let me know and I'll add them.
What does your memory usage look like? Might you be paging to disk?
Excerpt From http://paulstovell.com/blog/wpf-navigation
Page Lifecycles ....
Suppose your page required some kind of parameter data to be passed to it:
... When navigating, if you click
"Back", WPF can't possibly know what values to pass to the
constructor; therefore it must keep the page alive.
... If you navigate passing an object directly, WPF will keep the object alive.
I don't have an answer, but this Channel 9 (Microsoft) video is pretty good regarding XAML performance. Maybe it can help you in your problem.
http://channel9.msdn.com/Events/Build/2012/4-103
How can I access page resource element in C# coding? I have the following piece of code in my XAML. I want to access the image element in my C# Code, but it is not accessible.
<Page.Resources>
<DataTemplate x:Key="Standard250x250ItemTemplate">
<Grid HorizontalAlignment="Left" Width="150" Height="150">
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image x:Name="image" Source="{Binding Image}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" />
</Border>
</Grid>
</DataTemplate>
It is not accessible because a DataTemplate resource does not get instantiated until it is loaded. You would need to do something like this to load it first:
var dataTemplate = (DataTemplate)this.Resources["Standard250x250ItemTemplate"];
var grid = dataTemplate.LoadContent();
and then traverse the element tree to get to the Image.
A better approach in many scenarios is to define an attached dependency property or attached behavior that you can attach to your Image in XAML and write code related to the associated Image.
It depends on when you are trying to access it. If trying to access the image control of elements that have already been rendered then you can use ItemContainerGenerator like such:
//assumes using a ListView
var item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromItem(myModel);
// traverse children
var image = GetChildOfType<Image>(item);
// use the image!
private T GetChildOfType<T>(DependencyObject obj)
{
for(int i = 0; i< VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if(child is T) return child as T;
T item = GetChildOfType<T>(child);
if(item != null) return item;
}
return null;
}
If you need to change properties of the image, then that can be accomplished through binding as well.
I'm unable to figure out how to select an item programmatically in a ListView.
I'm attempting to use the listview's ItemContainerGenerator, but it just doesn't seem to work. For example, obj is null after the following operation:
//VariableList is derived from BindingList
m_VariableList = getVariableList();
lstVariable_Selected.ItemsSource = m_VariableList;
var obj =
lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);
I've tried (based on suggestions seen here and other places) to use the ItemContainerGenerator's StatusChanged event, but to no avail. The event never fires. For example:
m_VariableList = getVariableList();
lstVariable_Selected.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
lstVariable_Selected.ItemsSource = m_VariableList;
...
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
//This code never gets called
var obj = lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);
}
The crux of this whole thing is that I simply want to pre-select a few of the items in my ListView.
In the interest of not leaving anything out, the ListView uses some templating and Drag/Drop functionality, so I'm including the XAML here. Essentially, this template makes each item a textbox with some text - and when any item is selected, the checkbox is checked. And each item also gets a little glyph underneath it to insert new items (and this all works fine):
<DataTemplate x:Key="ItemDataTemplate_Variable">
<StackPanel>
<CheckBox x:Name="checkbox"
Content="{Binding Path=ListBoxDisplayName}"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
<Image ToolTip="Insert Custom Variable" Source="..\..\Resources\Arrow_Right.gif"
HorizontalAlignment="Left"
MouseLeftButtonDown="OnInsertCustomVariable"
Cursor="Hand" Margin="1, 0, 0, 2" Uid="{Binding Path=CmiOrder}" />
</StackPanel>
</DataTemplate>
...
<ListView Name="lstVariable_All" MinWidth="300" Margin="5"
SelectionMode="Multiple"
ItemTemplate="{StaticResource ItemDataTemplate_Variable}"
SelectionChanged="lstVariable_All_SelectionChanged"
wpfui:DragDropHelper.IsDropTarget="True"
wpfui:DragDropHelper.IsDragSource="True"
wpfui:DragDropHelper.DragDropTemplate="{StaticResource ItemDataTemplate_Variable}"
wpfui:DragDropHelper.ItemDropped="OnItemDropped"/>
So what am I missing? How do I programmatically select one or more of the items in the ListView?
Bind the IsSelected property of the ListViewItem to a property on your model. Then, you need only work with your model rather than worrying about the intricacies of the UI, which includes potential hazards around container virtualization.
For example:
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsGroovy}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Now, just work with your model's IsGroovy property to select/deselect items in the ListView.
Where 'this' is the ListView instance. This will not only change the selection, but also set the focus on the newly selected item.
private void MoveSelection(int level)
{
var newIndex = this.SelectedIndex + level;
if (newIndex >= 0 && newIndex < this.Items.Count)
{
this.SelectedItem = this.Items[newIndex];
this.UpdateLayout();
((ListViewItem)this.ItemContainerGenerator.ContainerFromIndex(newIndex)).Focus();
}
}
Here would be my best guess, which would be a much simpler method for selection. Since I'm not sure what you're selecting on, here's a generic example:
var indices = new List<int>();
for(int i = 0; i < lstVariable_All.Items.Count; i++)
{
// If this item meets our selection criteria
if( lstVariable_All.Items[i].Text.Contains("foo") )
indices.Add(i);
}
// Reset the selection and add the new items.
lstVariable_All.SelectedIndices.Clear();
foreach(int index in indices)
{
lstVariable_All.SelectedIndices.Add(index);
}
What I'm used to seeing is a settable SelectedItem, but I see you can't set or add to this, but hopefully this method works as a replacement.
In case you are not working with Bindings, this could also be a solution, just find the items in the source and add them to the SelectedItems property of your listview:
lstRoomLights.ItemsSource = RoomLights;
var selectedItems = RoomLights.Where(rl => rl.Name.Contains("foo")).ToList();
selectedItems.ForEach(i => lstRoomLights.SelectedItems.Add(i));