I am having problem in affecting to a TextBlock "TxtChoisie" the Content (Nom/Categorie) of a ListViewItem in a universal app,this is my code:
xaml code:
<TextBlock Foreground="#575855" FontSize="18 " x:Name="TxtChoisie" />
<ListView x:Name="listme" IsItemClickEnabled="True" SelectionMode="Single" ItemClick="listme_ItemClick">
<ListViewItem>
<TextBlock Text="Nom" HorizontalAlignment="Center" Margin="0" Foreground="#727271" />
</ListViewItem>
<ListViewItem>
<TextBlock Text="Categorie" HorizontalAlignment="Center" Margin="0" Foreground="#727271" />
</ListViewItem>
</ListView>
code behind:
private void listme_ItemClick(object sender, ItemClickEventArgs e)
{
var myClickedItem = e.ClickedItem.ToString(); ;
TxtChoisie.Text = myClickedItem;
}
what I get in my TextBlock is not the Content(like Categorie or Nom)
thanks for Help
ClickedItem is an object. Source
You will need to convert it to a TextBlock and then read the Text property to get the right value:
var myClickedItem = ((TextBlock)e.ClickedItem).Text;
TxtChoisie.Text = myClickedItem;
You can miss this local variable out:
TxtChoisie.Text = ((TextBlock)e.ClickedItem).Text;
You should also check that the clicked item is a TextBlock before casting:
var myClickedItem = e.ClickedItem as TextBlock;
if (myClickedItem != null)
{
TxtChoisie.Text = myClickedItem.Text;
}
or in C# 6 syntax:
TxtChoisie.Text = myClickedItem?.Text;
Related
<GridView x:Name="MainGridStations" ItemsSource="{x:Bind Stations}" IsItemClickEnabled="True" ItemClick="GridView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:Station">
<Grid x:Name="WantToSelectByCode">
<Grid Background="White" HorizontalAlignment="Center" Width="300" Height="200" VerticalAlignment="Center">
<Grid Background="#e4f0fc" Height="65" VerticalAlignment="Bottom" Opacity="0.8">
<TextBlock x:Name="StationName" Text="{Binding Name}" FontWeight="Bold" Foreground="#2c9a8b" HorizontalAlignment="Center" />
</Grid>
</Grid>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
I'm trying to select a child by index of a dynamically filled gridview but what i've tried always returns null.
Like so for the first child for example:
var container = MainGridStations.ContainerFromIndex(0);
var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;
What am I doing wrong here?
You can get the corresponding GridViewItem from the method ItemsControl.ContainerFromIndex(Int32) directly and don't need to use the VisualTreeHelper to get it again.
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem= container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Red);
The container have been the corresponding GridViewItem got from the index.
Note that: since your inner Grid have a Background="White" property configuration, you can delete the code to see the effect more obviously using my above code to change the gridViewItem.Background.
---Update---
You must get the GridViewItem after the items loaded. You can try the code in your GridView_ItemClick event handler or the page's loaded event hander. Also pay attention to my above note that to get more obvious effect, please delete the Background="White" in your above xaml code.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem = container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Green);
}
//get the item here
private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
var container = MainGridStations.ContainerFromIndex(0);
GridViewItem gridViewItem= container as GridViewItem;
gridViewItem.Background = new SolidColorBrush(Colors.Red);
//var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;
}
Is there a way I can get the index of a tapped item in the AdaptiveGridView toolkit.
Heres my code:
Page Resources:
<Page.Resources>
<DataTemplate x:Key="Photos">
<Grid>
<Image Source="{Binding ImageURL}"
Stretch="UniformToFill"
HorizontalAlignment="Center"
VerticalAlignment="Center">
</Image>
<TextBlock Text="{Binding ImageText}"
FontSize="20">
</TextBlock>
</Grid>
</DataTemplate>
</Page.Resources>
XAML:
<UWPToolkit:AdaptiveGridView x:Name="AdaptiveGV" ItemHeight="200" ItemClick="AdaptiveGV_ItemClick" DesiredWidth="200" ItemTemplate="{StaticResource Photos}"/>
Code behind:
List<Images> ImageCollection = new List<Images>();
ImageCollection.Add(new Images()
{
ImageURL = Response[i].ProjectImageURL,
ImageText = Response[i].ProjectName
});
}
AdaptiveGV.ItemsSource = ImageCollection;
I want the get an index of the item i clicked. Is there a way to do that?
I want the get an index of the item i clicked. Is there a way to do that?
Yes you can, in the ItemClickEventArgs, you can get the clicked item and its index like this:
private void AdaptiveGV_ItemClick(object sender, ItemClickEventArgs e)
{
var item = e.ClickedItem as Images;
var index = ImageCollection.IndexOf(item);
}
I have the following code:
<ScrollViewer x:Name="swipeBetweenPages" Grid.Row="1">
<Pivot DataContext="{StaticResource ViewModel}" x:Name="pivot" Margin="0,-45,0,0"
HeaderTemplate="{StaticResource headerTest}"
ItemTemplate="{StaticResource pivotTemplate}" ItemsSource="{Binding Articles}" SelectionChanged="pivot_SelectionChanged">
</Pivot>
</ScrollViewer>
<Page.Resources>
<ViewModels:ArticleViewModel x:Key="ViewModel" />
<DataTemplate x:Key="headerTest">
</DataTemplate>
<DataTemplate x:Key="pivotTemplate">
<StackPanel Margin="-15 0 -15 0">
<Grid>
<Grid.Background>
<ImageBrush AlignmentX="Center" AlignmentY="Center" ImageSource="Assets/PlaceHolder.jpg"></ImageBrush>
</Grid.Background>
<Image q42controls:ImageExtensions.CacheUri="{Binding ImageURL}" Tag="{Binding ImageURL}" Tapped="ImageView"></Image>
</Grid>
<StackPanel Background="White">
<TextBlock x:Name="HeadLine" Text="{Binding HeadLine}"
Margin="10 5 0 -5" TextWrapping="Wrap"
FontSize="20" Foreground="Black"
FontFamily="{StaticResource HeadlineCommonFamiy}"
Pivot.SlideInAnimationGroup="GroupTwo" Height="63"
FontWeight="Bold" TextTrimming="CharacterEllipsis"/>
<TextBlock Text="{Binding Abstract}" TextWrapping="Wrap" FontSize="15" FontStyle="Italic"
Pivot.SlideInAnimationGroup="GroupTwo" Margin="10 5 0 10"
FontFamily="{StaticResource AbstractCommonFamily}"/>
</StackPanel>
<StackPanel x:Name="descriptionSP" Background="White">
<RichTextBlock IsTextSelectionEnabled="False" x:Name="richTextBlock"
local:Properties.Html="{Binding ArticleDetail}" TextWrapping="Wrap"
Pivot.SlideInAnimationGroup="GroupTwo" Margin="10 5 0 10"
FontFamily="{StaticResource ContentControlThemeFontFamily}">
</RichTextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
I am trying to set the font size to rich text block in the back end dynamically.
Now, I am trying with the following code in the C# end:
private T FindElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
RichTextBlock richTextBlock = new RichTextBlock();
StackPanel rootStackPanel = new StackPanel();
StackPanel childStackPanel = new StackPanel();
PivotItem item = (sender as Pivot).ContainerFromItem((sender as Pivot).SelectedItem) as PivotItem;
rootStackPanel = item.ContentTemplate.LoadContent() as StackPanel;
childStackPanel = rootStackPanel.FindName("descriptionSP") as StackPanel;
richTextBlock = rootStackPanel.FindName("richTextBlock") as RichTextBlock;
Paragraph paragraph = new Paragraph();
Run run = new Run();
// Customize some properties on the RichTextBlock.
richTextBlock.IsTextSelectionEnabled = true;
richTextBlock.SelectionHighlightColor = new SolidColorBrush(Windows.UI.Colors.Pink);
richTextBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.Blue);
richTextBlock.FontWeight = Windows.UI.Text.FontWeights.Light;
richTextBlock.FontFamily = new FontFamily("Arial");
richTextBlock.FontStyle = Windows.UI.Text.FontStyle.Italic;
richTextBlock.FontSize = 50;
//run.Text = "This is some sample text to demonstrate some properties.";
paragraph.Inlines.Add(run);
richTextBlock.Blocks.Add(paragraph);
// Add the RichTextBlock to the visual tree (assumes stackPanel is decalred in XAML).
//childStackPanel.Children.Add(richTextBlock);
//rootStackPanel.Children.Add(richTextBlock);
But, it is not affecting the font size.
Please help me.
Thanks.
You can create a Property in your ViewModel or code behind file and use data binding to connect it to the FontSize property.
private double _myFontSize;
public double MyFontSize
{
get{ return _myFontSize; }
set{ _myFontSize = value; }
}
Now inside your data template for the font size of the rich text box,
FontSize="{Binding MyFontSize, ElementName=page/viewModel}"
And remember to use 'INotifyPropertyChanged' to notify the UI when the value of your property changes. This web site provides a guide on implementing 'INotifyPropertyChanged'
I have the following code:
<ScrollViewer x:Name="swipeBetweenPages" Grid.Row="1">
<Pivot DataContext="{StaticResource ViewModel}" x:Name="pivot" Margin="0,-45,0,0"
HeaderTemplate="{StaticResource headerTest}"
ItemTemplate="{StaticResource pivotTemplate}" ItemsSource="{Binding Articles}" SelectionChanged="pivot_SelectionChanged">
</Pivot>
</ScrollViewer>
<Page.Resources>
<ViewModels:ArticleViewModel x:Key="ViewModel" />
<DataTemplate x:Key="headerTest">
</DataTemplate>
<DataTemplate x:Key="pivotTemplate">
<StackPanel Margin="-15 0 -15 0">
<Grid>
<Grid.Background>
<ImageBrush AlignmentX="Center" AlignmentY="Center" ImageSource="Assets/PlaceHolder.jpg"></ImageBrush>
</Grid.Background>
<Image q42controls:ImageExtensions.CacheUri="{Binding ImageURL}" Tag="{Binding ImageURL}" Tapped="ImageView"></Image>
</Grid>
<StackPanel Background="White">
<TextBlock x:Name="HeadLine" Text="{Binding HeadLine}"
Margin="10 5 0 -5" TextWrapping="Wrap"
FontSize="20" Foreground="Black"
FontFamily="{StaticResource HeadlineCommonFamiy}"
Pivot.SlideInAnimationGroup="GroupTwo" Height="63"
FontWeight="Bold" TextTrimming="CharacterEllipsis"/>
<TextBlock Text="{Binding Abstract}" TextWrapping="Wrap" FontSize="15" FontStyle="Italic"
Pivot.SlideInAnimationGroup="GroupTwo" Margin="10 5 0 10"
FontFamily="{StaticResource AbstractCommonFamily}"/>
</StackPanel>
<StackPanel x:Name="descriptionSP" Background="White">
<RichTextBlock IsTextSelectionEnabled="False" x:Name="richTextBlock"
local:Properties.Html="{Binding ArticleDetail}" TextWrapping="Wrap"
Pivot.SlideInAnimationGroup="GroupTwo" Margin="10 5 0 10"
FontFamily="{StaticResource ContentControlThemeFontFamily}">
</RichTextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
How to get the RichTextBlock control inside the stackpanel?
Now, I am trying with the following code in the C# end:
private T FindElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
RichTextBlock richTextBlock = new RichTextBlock();
StackPanel rootStackPanel = new StackPanel();
StackPanel childStackPanel = new StackPanel();
PivotItem item = (sender as Pivot).ContainerFromItem((sender as Pivot).SelectedItem) as PivotItem;
rootStackPanel = item.ContentTemplate.LoadContent() as StackPanel;
childStackPanel = rootStackPanel.FindName("descriptionSP") as StackPanel;
richTextBlock = rootStackPanel.FindName("richTextBlock") as RichTextBlock;
Paragraph paragraph = new Paragraph();
Run run = new Run();
// Customize some properties on the RichTextBlock.
richTextBlock.IsTextSelectionEnabled = true;
richTextBlock.SelectionHighlightColor = new SolidColorBrush(Windows.UI.Colors.Pink);
richTextBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.Blue);
richTextBlock.FontWeight = Windows.UI.Text.FontWeights.Light;
richTextBlock.FontFamily = new FontFamily("Arial");
richTextBlock.FontStyle = Windows.UI.Text.FontStyle.Italic;
richTextBlock.FontSize = 50;
//run.Text = "This is some sample text to demonstrate some properties.";
//Add the Run to the Paragraph, the Paragraph to the RichTextBlock.
paragraph.Inlines.Add(run);
richTextBlock.Blocks.Add(paragraph);
// Add the RichTextBlock to the visual tree (assumes stackPanel is decalred in XAML).
//childStackPanel.Children.Add(richTextBlock);
//rootStackPanel.Children.Add(richTextBlock);
But I am not able to get the control RichTextBlock. I am getting a null value.
Please help me.
Thanks.
You can use ContentTemplate of PivotItem to get the template of PivotItem for example like this:
PivotItem item = (sender as Pivot).ContainerFromItem((sender as Pivot).SelectedItem) as PivotItem;
var rootStackPanel = item.ContentTemplate.LoadContent() as StackPanel;
var richtb = rootStackPanel.FindName("richtb") as RichTextBlock;
And I firstly gave a name to the RichTextBlock as "richtb".
The code you provided searches the tree for the first matching control of the given type. This means, that what you get in return is the first StackPanel in the XAML definition, but the RichTextBlock in the second one.
Why don't you directly do this, instead of searching for the StackPanel:
var richTextBlock = FindElementInVisualTree<RichTextBlock>(item);
This will return the RichTextBlock directly, because the FindElementInVisualTree method is searching down the tree recursively.
I'm using a ListBox to display all values contained in Dictionary<> object:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Content is filled by the following code:
Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.
I tried doing something like that, but obviosly it doesn't work:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
I would really appreciate your help!
you can even do the follwing:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
<TextBlock Text="{Binding Value}"/>
</Grid>
So you don't need code behind...
BR,
TJ
There are several problems:
In Xaml you probably don't want to display the class name, but a reasonable string, for example:
<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />
In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
Contact c = (Contact)kv.Value;
Debug.WriteLine(c.LastName);
}
Your code is good, using ListBox.SelectedItem is the right approach.
I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
var dataContext = lbi.DataContext;
this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
Try this it works for me, will help you to...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox ContactListBox = sender as ListBox;
ListBoxItem listBoxItem = ContactListBox .ItemContainerGenerator.ContainerFromItem(ContactListBox.SelectedItem) as ListBoxItem;
if (listBoxItem == null)
{
return;
}
TextBlock txtBlock = FindVisualChildByName(listBoxItem, "ListTextBlock");
MessageBox.Show(txtBlock.Text);
}
private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(NameProperty) as string;
if (controlName == name)
{
return child as T;
}
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
will go something like this..
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
DataTemplate template=lb.ContentTemplate;
//Now here you have to extract the content of the data template
and then you need to extract the TextBlock from that content.
}
This is just an overview of the functionality.Sorry not able to post complete code.