I have a TreeView which is binded to a OberservableCollection. When I add Items to that List everything works, except that the indentation of the TreeView is missing. All TreeViewItems have the same level of indentation, regardless of their level insinde the treeview. The problem with that is that you can't really see which element is at which level.
The Item class contains a list of other Items called "Children", a string called "ItemName" and a BitmapImage called "ImageSource".
I already tried it without bindings. I simply added new TreeViewItems on events, but I had the same problem with that.
Here is my XAML Code for that TreeView:
<TreeView Grid.Column="0" Name="ProjectTree" ItemsSource="{Binding ItemList, Mode=TwoWay}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type ViewItems:Item}" ItemsSource="{Binding Path=Children, Mode=TwoWay}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="22"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding ImageSource}" RenderOptions.BitmapScalingMode="HighQuality" Grid.Column="0" Width="20" Margin="1"/>
<TextBlock Text="{Binding ItemName}" Grid.Column="1" VerticalAlignment="Center"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
The bindings are fine, as I said. It is only the indentation that doesn't work.
I'd be glad if you people could help me.
Related
Referencing this example:
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-bind-to-a-collection-and-display-information-based-on-selection
(some relevant code snippets:)
<Window.Resources>
<local:People x:Key="MyFriends"></local:People>
<DataTemplate x:Key="DetailTemplate">
<Border Width="300" Height="100" Margin="20"
BorderBrush="Aqua" BorderThickness="1" Padding="8">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="First Name:"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Last Name:"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Home Town:"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=HomeTown}"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<ListBox Width="200" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
<ContentControl x:Name="contentControl1"
Content="{Binding Source={StaticResource MyFriends}}"
ContentTemplate="{StaticResource DetailTemplate}" />
Both ListBox.ItemsSource and ContentControl.Content bind to the same source (MyFriends, an instance of the People class which derives from ObservableCollection<Person>). If my understanding is correct, this means that both the ListBox.ItemsSource and ContentControl.Content properties will be bound to the same implicitly created instance of ListCollectionView.
I understand that setting ListBox.IsSynchronizedWithCurrentItem="True" synchronizes ListBox.SelectedItem and ItemCollection.CurrentItem.
DetailTemplate (above) displays the details of the selected ListBox item, despite being 'bound' to a ListCollectionView. Specifying Path=/ (what I thought would be necessary to achieve the resulting behavior) does not have any effect - it's as if WPF knows to do it implicitly somehow:
<ContentControl x:Name="contentControl1"
Content="{Binding Source={StaticResource MyFriends}, Path=/}"
ContentTemplate="{StaticResource DetailTemplate}" />
As a test, I created another ContentControl with Content bound to a DataTemplate containing a ListBox:
<ContentControl x:Name="contentControl2"
Content="{Binding Source={StaticResource MyFriends}}"
ContentTemplate="{StaticResource DetailTemplate2}" />
<DataTemplate x:Key="DetailTemplate2">
<ListBox ItemsSource="{Binding}"></>
</DataTemplate>
And it displayed the list.
My question is: Why does DataTemplate get the selected Person object while the ListBox and DetailTemplate2 get the People collection?
(the behavior is desirable, I just don't understand what black magic is occurring under the hood to make it so)
Is a good question! I didn't notice that until read your post. So, after did some digging from source code of PropertyPathWorker, it appears that when PropertyPathWorker failed to solve a member of an object, in your case, it try to solve 'FirstName', 'LastName' ect. with 'MyFriends', it will try to solve it with the view of the object. And if still failed, it will try to solve it with view's CurrentItem, and that's where the magic happened. You can find those codes in PropertyPathWorker.UpdateSourceValueState(int k, ICollectionView collectionView, object newValue, bool isASubPropertyChange) and PropertyPathWorker.ReplaceItem(int k, object newO, object parent).
So, I've been working on a legend for our map using a WPF treeview to display the groups and layers.
I've gotten it working and displaying just fine, but when I scroll the treeview with the mousewheel, the control starts flickering and the vertical scrollbar for the tree keeps resizing up and down.
The treeview layout is like this:
Group
Layer
Layer sub items
Layer
Layer sub items
Layer
Layer sub items
Group
Layer
etc...
The Group and Layer nodes are tree view items, but the layer sub items are contained within an items control. The layer sub items are not meant to be expanded/contracted, or selected and thus must remain static under the layer node, thus the items control seemed like a sensible choice.
When I scroll with the mouse wheel all the way to the top or bottom of the tree view, the scrollbar starts flicking and resizing, the last few elements of the items control flickers in and out of view (when it shouldn't be in view at all), and sometimes, the tree view will actually scroll back and forth.
If I remove the items control, everything works as it's supposed to. And when I add it back in, it messes up.
Also, if I grab the scroller thumb with the mouse and drag it, everything works fine. No jumping around.
Here's the resource XAML for the control:
<views:DynamicLegendNodeTemplateSelector x:Key="LegendTemplateSelector">
<views:DynamicLegendNodeTemplateSelector.GroupTemplate>
<HierarchicalDataTemplate DataType="{x:Type legend:IDynamicMapLegendGroup}">
<HierarchicalDataTemplate.ItemsSource>
<MultiBinding Converter="{StaticResource LegendNode}">
<Binding Path="Groups"/>
<Binding Path="LegendLayers"/>
</MultiBinding>
</HierarchicalDataTemplate.ItemsSource>
<Grid>
<StackPanel Orientation="Horizontal">
<CheckBox Focusable="False" IsChecked="{Binding IsVisible}" VerticalAlignment="Center">
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center"/>
</CheckBox>
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</views:DynamicLegendNodeTemplateSelector.GroupTemplate>
<views:DynamicLegendNodeTemplateSelector.LayerTemplate>
<HierarchicalDataTemplate DataType="{x:Type legend:IDynamicMapLayerLegendItem}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Focusable="False" IsChecked="{Binding IsVisible}" VerticalAlignment="Center">
<TextBlock Text="{Binding LayerCaption}" VerticalAlignment="Center"/>
</CheckBox>
<ItemsControl Grid.Row="1"
Margin="16,0,0,0"
BorderThickness="0"
Background="Transparent"
ItemsSource="{Binding LegendItems, IsAsync=True}"
HorizontalAlignment="Left"
HorizontalContentAlignment="Left"
MouseWheel="ItemControls_MouseWheel"
ScrollViewer.CanContentScroll="False"
MouseUp="ItemsControl_MouseUp">
<ItemsControl.Template>
<ControlTemplate>
<ItemsPresenter/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Width="20" Height="20" Stretch="UniformToFill" Source="{Binding Symbol}"/>
<Label Grid.Column="1" Content="{Binding Label}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</HierarchicalDataTemplate>
</views:DynamicLegendNodeTemplateSelector.LayerTemplate>
</views:DynamicLegendNodeTemplateSelector>
<Style x:Key="TreeItemStyle" TargetType="TreeViewItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<EventSetter Event="MouseUp" Handler="TreeViewItem_MouseUp"></EventSetter>
</Style>
And here's the treeview:
<TreeView x:Name="LegendHierarchy"
MinWidth="200"
ItemsSource="{Binding LegendItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:DynamicArcGisRuntimeMapLegendView}}}"
ItemContainerStyle="{StaticResource TreeItemStyle}"
ItemTemplateSelector="{StaticResource LegendTemplateSelector}" />
This code is using .NET 4.5 in Visual Studio 2015 if that matters.
Regardless, does anyone know what might be causing the problem?
Thanks
So, it goes to show that an attempt at a good nights sleep is helpful.
Apparently, all I had to do was set
VirtualizingPanel.VirtualizationMode="Recycling"
On the treeview control and it starting working.
Here's the full tree view XAML:
<TreeView x:Name="LegendHierarchy"
MinWidth="200"
ItemsSource="{Binding LegendItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:DynamicArcGisRuntimeMapLegendView}}}"
ItemContainerStyle="{StaticResource TreeItemStyle}"
ItemTemplateSelector="{StaticResource LegendTemplateSelector}" UseLayoutRounding="True" ScrollViewer.CanContentScroll="True" HorizontalContentAlignment="Stretch"
VirtualizingPanel.VirtualizationMode="Recycling"/>
I hope this helps others.
<ListView Name="myList" Background="Transparent" Margin="15,88,15,15">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid Height="100">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Margin="5">
<TextBlock Name="xName" Text="{Binding Name}" FontSize="30" Margin="10,0,5,0" FontWeight="Medium"/>
<TextBlock Name="xNo" Text="{Binding No}" FontSize="25" Margin="10,0,5,0" TextTrimming="CharacterEllipsis"/>
</StackPanel>
<Grid Grid.Column="1" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<RadioButton Grid.Column="0" Name="r1" Content="1" Width="10" Margin="5,15,-2,5"/>
<RadioButton Grid.Column="1" Name="r2" Content="2" Width="10" Margin="5,15,-2,5"/>
</Grid>
</Grid>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Now I want to retrieve each item in ListView i.e, the controls in it. The TextBlocks content and to know which RadioButton is selected.
I tried taking classes like this
public class Att
{
public string Name;
public string No;
public RadioButton r1;
public RadioButton r2;
}
There are separate sources for the content of the TextBoxes in the ListView. They come from different classes. I tried retrieving the items using above class Att.
But it is showing some type conversion errors. Please anyone help me! I'm a beginner.
Thanks is advance.
Thanks for all the support!
Well I tried doing this on my own and finally I got it. What I really wanted is to know which RadioButton is checked. I tried taking class Att for retrieving the items in ListView. I made modifications to the Att Class and added properties r1 and r2 of type bool instead of RadioButton and binded this property to the IsChecked property of the RadioButton in XAML and also mode of binding is TwoWay. So the changes done in the XAML can be reflected in the source list of items.
I am currently building a Windows Phone Applicaation, based off of the HubAppTemplate.
The template comes with a sample .JSON data source that it uses to populate the data of each HubSection. However, I want to use a non JSON type of data as the basis of my code. Inside my C# code, I need to make a function call to my backend to get the type of data I want out of it.
I can put this data inside of my own custom list (on the C# side), but how can I make that list act as the data source for my HubSection? Any old listview/list box works perfectly. Basically, I need help wiring the C# to the XAML -- the main issue is that I cannot access my listView inside of the datatemplate by name.
Can anyone give me some pointers to get going in the right direction?
Here is some reference code to show you what I am talking about:
<HubSection x:Uid="Clubs" Header="Clubs" DataContext="{Binding Groups}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
<DataTemplate>
<ListView Name="ClubsList"
IsItemClickEnabled="True"
ItemsSource="{Binding}"
ItemClick="GroupSection_ItemClick"
ContinuumNavigationTransitionInfo.ExitElementContainer="True">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,27.5">
<TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</HubSection>
The above XAML is basically pulled straight from the hubapp template. I want to be able to use my own itemssource inside of that ListView that is generated from my C# code -- however, I cannot figure out how this ItemsSource works. I also cannot access my listview by name (ClubsList).
Here is the initialization code going on up top (wasn't sure if it was important to post this or not):
<Page
x:Class="HubAppTemplate.HubPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HubAppTemplate"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:HubAppTemplate.Data"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
d:DataContext="{Binding Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="HubSectionHeaderTemplate">
<TextBlock Margin="0,0,0,-9.5" Text="{Binding}"/>
</DataTemplate>
<!-- Grid-appropriate item template as seen in section 2 -->
<DataTemplate x:Key="Standard200x180TileItemTemplate">
<Grid Margin="0,0,9.5,9.5" Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="138.5" Width="138.5"/>
<TextBlock Text="{Binding Title}" VerticalAlignment="Bottom" Margin="9.5,0,0,6.5" Style="{ThemeResource BaseTextBlockStyle}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="StandardTripleLineItemTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
</Border>
<StackPanel Grid.Column="1" Margin="14.5,0,0,0">
<TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
<TextBlock Text="{Binding Description}" Style="{ThemeResource ListViewItemContentTextBlockStyle}" Foreground="{ThemeResource PhoneMidBrush}" />
<TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}" />
</StackPanel>
</Grid>
</DataTemplate>
<DataTemplate x:Key="StandardDoubleLineItemTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
</Border>
<StackPanel Grid.Column="1" Margin="14.5,0,0,0">
<TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
<TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
</StackPanel>
</Grid>
</DataTemplate>
</Page.Resources>
<Grid x:Name="LayoutRoot">
<Hub x:Name="Hub" x:Uid="Hub" Header="Club Alert" Background="{ThemeResource HubBackgroundImageBrush}">
It is pulling from the JSON backend, but I want to just use my own custom listview for each section. Deleting the DataSource and data template headers gives me errors, however.
Thank you so much for your help in advance!
--A total newbie
HubSection elements require their contents to be populated via a template, so you can't just remove the <DataTemplate> tags, unfortunately. However, there is a simple way to accomplish what you are trying to do, if I understand you correctly.
If you're starting with the default Hub template, you should have this function in your HubPage.xaml.cs file
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
this.DefaultViewModel["Groups"] = sampleDataGroups;
MainViewModel viewModel = DataContext as MainViewModel;
if (!viewModel.IsDataLoaded)
{
viewModel.Load();
}
}
this.DefaultViewModel is just a Dictionary, and they have loaded the sample JSON into a variable and stored this in the ["Groups"] key of the dictionary. Since the Page's DataContext is being bound to {Binding DefaultViewModel, RelativeSource={RelativeSource Self}}, the HubSection's DataContext is being bound to {Binding Groups}, and the ItemsSource of the ListView in each DataTemplate is being bound to {Binding}, each element of the loaded JSON is being used to fill the items of the ListView.
A simple solution would be to assign this.DefaultViewModel["Groups"] to the C# List you are creating from the data you load from your back end.
Something like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var myData = await GetListOfThingsFromBackend();
this.DefaultViewModel["Groups"] = myData;
MainViewModel viewModel = DataContext as MainViewModel;
if (!viewModel.IsDataLoaded)
{
viewModel.Load();
}
}
A better approach would probably be to separate out all ViewModel functionality to it's own class that is better suited to your needs, and then adjust the various DataContext properties throughout the XAML, but that would likely take more time. I can elaborate if needed, but the simple solution is probably enough for now.
I have a listbox and I need a way to pass the selected item to a UserControl.
How can I do it?
<Grid >
<ListBox Name="lbPersonaggi" HorizontalContentAlignment="Stretch" SelectionMode="Single"><!--SelectionChanged="lbPersonaggi_SelectionChanged"-->
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Name="TBPG" Text="{Binding Personaggio}" MouseUp="ClickPG" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
If you just want to set the selected item as DataContext for another UserControl you write something like this
<UserControl DataContext="{Binding lbPersonaggi.SelectedItem}" />
You don't need a property in your viewmodel to store the selected item.
Try this in your ListBox Definition header:
SelectedItem="{Binding Path=YourPropertyWhereYouWantToStoreTheValue, Mode=OneWayToSource}"
And then Re-use this property in your second Control.
I think it will work.