I have this code:
<HubSection x:Name="MyHub">
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="200"></RowDefinition>
</Grid.RowDefinitions>
<Image x:Name="MYImage" Source="{Binding image}" Height="50" Width="60" VerticalAlignment="Center"/>
<StackPanel Orientation="Vertical">
<TextBlock TextWrapping="Wrap" Width="200" VerticalAlignment="Center" HorizontalAlignment="Left" Text="{Binding name}"/>
<Button Content="Click me">
</StackPanel>
</Grid>
</DataTemplate>
</HubSection>
But I do not know how to access the text-block, I want to change the foreground color of the text-block in code behind.
XAML:
<Hub x:Name="myHub">
<HubSection x:Name="myHubSection">
<DataTemplate>
<TextBlock x:Name="textbox1" Text="text" Width="300" Height="100">
</TextBlock>
</DataTemplate>
</HubSection>
</Hub>
Code behind:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
var hub_section = FindVisualChildByName<HubSection>(this.myHub, "myHubSection");
var text_box = FindVisualChildByName<WebView>(hub_section, "textbox1");
}
public 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(Control.NameProperty) as string;
if (controlName == name)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
}
return null;
}
More detailed information you could refer to How to access a Control inside the data template in C# Metro UI in the code behind
Related
I have json as below:
I want to display the data in the gallery on the gridview, then if the user clicks the image on the gridview, it will show a picture with a larger size on the flipview according to the selected image. I'm having trouble, that is when the image on the gridview is selected, it always shows up the image on the flipview for the first index (not in accordance with the picture chosen by the user).
XAML:
<callisto:CustomDialog x:FieldModifier="public" x:Name="ArticleDetail"
Grid.Row="0" Grid.RowSpan="2" Title=""
Background="White" BackButtonVisibility="Collapsed" BorderBrush="White" >
<ScrollViewer Margin="0,0,5,5" Background="{x:Null}" VerticalScrollBarVisibility="Auto" HorizontalScrollMode="Disabled">
<StackPanel Height="auto">
<ProgressRing x:Name="articleDetailLoading" HorizontalAlignment="Center" VerticalAlignment="Center" Height="50" Width="50" />
<StackPanel x:Name="articleDetailBox" Margin="0,0,10,10" Height="auto">
<Grid x:Name="articleDetailGrid" BorderBrush="#FF990000" BorderThickness="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="articleIdDetail" Grid.Row="0" Text="{Binding ID}" Visibility="Collapsed"/>
<AppBarButton x:Name="closeArticleBtn" Icon="Clear" HorizontalAlignment="Right" Foreground="Black" Click="closeArticleBtn_Click"/>
<ScrollViewer x:Name="articleTitleScroll" Grid.Row="1" Margin="10,0,0,0" Width="650" Height="50" VerticalAlignment="Top" HorizontalAlignment="Left" VerticalScrollBarVisibility="Auto" Background="{x:Null}" HorizontalScrollMode="Disabled">
<TextBlock x:Name="articleTitleDetail" Margin="0,0,15,15" FontSize="18" FontFamily="Segoe UI Black" FontWeight="SemiBold" TextWrapping="Wrap" Height="auto" TextAlignment="Center"/>
</ScrollViewer>
<TextBlock x:Name="articleDateDetail" Grid.Row="3" Margin="10,15,10,0" FontSize="15" FontFamily="Segoe UI Black" FontWeight="SemiLight" TextWrapping="Wrap" Height="auto" TextAlignment="Center"/>
<GridView x:Name="articleImageGridView" Grid.Row="5" Margin="10,25,10,0" Height="110" AutomationProperties.AutomationId="ItemDetailScrollViewer" DataContext="{Binding SelectedItem, ElementName=itemListView}"
ScrollViewer.HorizontalScrollMode="Auto" ScrollViewer.VerticalScrollMode="Auto" IsItemClickEnabled="True"
ScrollViewer.ZoomMode="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemClick="articleImageGridView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="90" Width="120" Margin="5,0,0,0" Background="{x:Null}" BorderBrush="#FF646464" BorderThickness="0.5">
<Border x:Name="coverBox" Grid.Row="0" Margin="0,0,0,0" Width="120" Height="90" VerticalAlignment="Top" HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="0.5">
<Border.Background>
<ImageBrush Stretch="UniformToFill" ImageSource="images/IP-placeholder.png"/>
</Border.Background>
<Image x:Name="cover" Source="{Binding ImageURL1}" HorizontalAlignment="Center" Stretch="Uniform" AutomationProperties.Name="{Binding Title}" ImageOpened="Image_ImageOpened" Loaded="cover_Loaded" Loading="cover_Loading"/>
</Border>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Vertical" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
<WebView x:Name="articleContentDetail" Grid.Row="6" Margin="10,15,10,10" Width="650" Height="150" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>
</StackPanel>
<StackPanel x:Name="articleFullImageDetailBox" Margin="0,0,10,10" Height="auto" Visibility="Collapsed">
<Grid x:Name="articleFullImageDetailGrid" BorderBrush="#FF990000" BorderThickness="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<AppBarButton x:Name="closearticleFullImageBtn" Grid.Column="1" Icon="Clear" HorizontalAlignment="Right" Foreground="Black" Click="closearticleFullImageBtn_Click"/>
<TextBlock x:Name="articleFullIdDetail" Grid.Row="0" Text="{Binding ID}" Visibility="Collapsed"/>
<FlipView x:Name="articleImageFullFlipview" Grid.Row="1" Grid.RowSpan="3" Grid.Column="0" Margin="0,0,0,0" ItemsSource="{Binding gallery.Items}" SelectedItem="{Binding gallery, Mode=TwoWay}" Width="650" Height="500" VerticalAlignment="Center" HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="1" Background="{x:Null}">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid x:Name="content" Margin="0,0,0,0">
<Border x:Name="coverBox" Width="600" Height="500">
<Border.Background>
<ImageBrush Stretch="Uniform" ImageSource="images/IP-placeholder.png"/>
</Border.Background>
<Image x:Name="cover" Source="{Binding ImageURLFull}" HorizontalAlignment="Center" Stretch="UniformToFill" AutomationProperties.Name="{Binding ID}" ImageOpened="Image_ImageOpened" Loaded="cover_Loaded" Loading="cover_Loading"/>
</Border>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
</StackPanel>
</StackPanel>
</ScrollViewer>
</callisto:CustomDialog>
Code:
ObservableCollection<ArticleClass> articleDatasourceDetailImage = new ObservableCollection<ArticleClass>();
articleDatasourceDetailImage.Clear();
articleDetailLoading.Visibility = Visibility.Visible;
articleDetailLoading.IsActive = true;
articleDetailBox.Visibility = Visibility.Collapsed;
articleFullImageDetailBox.Visibility = Visibility.Collapsed;
ArticleDetail.IsOpen = true;
articleItemDetail = e.ClickedItem as ArticleClass;
articleIdDetail.Text = articleItemDetail.ID.ToString();
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
articleDetailLoading.IsActive = true;
try
{
string urlPath = "http://indonesia-product.com/api/v1/articles/"10.json?module=articles&page=1&token=3f63-dc43-c8d5-eb45-8cbf-b72d-9d98-800f";
//Debug.WriteLine(urlPath.ToString());
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
HttpResponseMessage response = await httpClient.GetAsync(urlPath);
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
articleDetailLoading.IsActive = false;
RequestException();
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject groupObject1 = jsonData.GetObject();
double id = groupObject1["id"].GetNumber();
string title = groupObject1["title"].GetString();
string date = groupObject1["publication_date"].GetString();
JsonArray jsonGallery = groupObject1["gallery"].GetArray();
foreach (JsonValue groupValue1 in jsonGallery)
{
JsonObject groupObject2 = groupValue1.GetObject();
string imageUrl = groupObject2.ContainsKey("image_url") && groupObject2["image_url"] != null ? groupObject2["image_url"].GetString() : string.Empty;
ArticleClass fileImage = new ArticleClass();
fileImage.ImageURL1 = imageUrl;
articleDatasourceDetailImage.Add(fileImage);
}
articleImageGridView.ItemsSource = articleDatasourceDetailImage;
articleDetailLoading.IsActive = false;
ArticleClass file = new ArticleClass();
file.ID = Convert.ToInt32(id);
file.Title = title;
DateTime dateConvert = Convert.ToDateTime(date);
file.Date = dateConvert.ToString("MMM d, yyyy");
articleContentDetail.NavigateToString(contentText);
articleDetailLoading.IsActive = false;
articleDetailBox.Visibility = Visibility.Visible;
articleDetailLoading.Visibility = Visibility.Collapsed;
articleDetailLoading.IsActive = false;
}
catch (HttpRequestException ex)
{
articleDetailLoading.IsActive = false;
}
}
else
{
articleDetailLoading.IsActive = false;
}
}
private async void articleImageGridView_ItemClick(object sender, ItemClickEventArgs e)
{
articleDetailLoading.Visibility = Visibility.Visible;
articleDetailLoading.IsActive = true;
articleDetailBox.Visibility = Visibility.Collapsed;
articleFullImageDetailBox.Visibility = Visibility.Collapsed;
var articleImageGridView = (GridView)sender;
articleImageFullFlipview.SelectedIndex = articleImageGridView.SelectedIndex;
articleFullImageDetailBox.Visibility = Visibility.Visible;
articleDetailLoading.Visibility = Visibility.Collapsed;
articleDetailLoading.IsActive = false;
}
How to handle it?
First, there is no need to get your data again when clicking on the item. When you load your data, set the ItemsSource of your GridView and your FlipView to be the same collection.
Second, when your item is clicked, get the SelectedIndex of the item and then set the SelectedIndex of your FlipView
private async Task LoadData()
{
// get data
var response = await httpClient.GetAsync(url);
// Convert to your objects
articleImageFullFlipview.ItemsSource = data;
articleImageGridView.ItemsSource = data;
}
private void articleImageGridView_ItemClick(object sender, ItemClickEventArgs e)
{
var gridView = (GridView)sender;
articleImageFullFlipview.SelectedIndex = gridView.SelectedIndex;
// show or hide any controls
}
<ListView Height="Auto" Name="lstIndent" SelectionMode="Single" Grid.ColumnSpan="5" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Row="0" >
<ListView.View >
<GridView x:Name="dgIndentDetails" >
<GridViewColumn Width="Auto" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<!--<GroupBox Header="Department Issue Header" Grid.Row="5" Grid.ColumnSpan="5" HorizontalAlignment="Stretch" >-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Grid.Column="0" IsChecked="{Binding Path=IsIndentIssue, UpdateSourceTrigger=PropertyChanged}" x:Name="chkbxIsChecked" HorizontalAlignment="Center"/>
<Label Grid.Column="1" Grid.Row="0" Content="{Binding ItemName}" x:Name="lbllstItemName" HorizontalAlignment="Center" ></Label>
<Label Grid.Column="2" Grid.Row="0" Content="{Binding Quantity}" x:Name="lbllstQty" HorizontalAlignment="Center" ></Label>
<Label Grid.Column="3" Grid.Row="0" Content="{Binding IssueQuantity}" x:Name="lbllstIssuedQty" HorizontalAlignment="Center" ></Label>
<DataGrid Height="Auto" Padding="10,10,10,10" Width="800" Grid.Row="1" Grid.ColumnSpan="5" Name="dgIssuedItemsBatchDetails" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ItemName}">
<DataGridTextColumn.Header>
<TextBlock Text="ItemName"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding BatchNo}">
<DataGridTextColumn.Header>
<TextBlock Text="BatchNo"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Quantity}">
<DataGridTextColumn.Header>
<TextBlock Text="Quantity"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<!--</GroupBox>-->
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
I need to find DataGrid dgIssuedItemsBatchDetails and then bind. That DataGrid is placed inside GridView and that GridView is placed inside ListView.
GridView grdvwIssueDetail = (GridView)lstIndent.FindName("dgIndentDetails");
By using this code I am able to find the GridView. My DataGrid is placed inside GridView DataTemplate. So suggest me how I can find my DataGrid from code behind.
It can be achieved by using VisualTreeHelper.
As MSDN says:
VisualTreeHelper class provides utility methods that perform common tasks involving nodes in a visual tree.
So let me show an example how it can be achieved:
private void SeeTheChild()
{
DataGrid myCombo = GetVisualChildInDataTemplate<DataGrid>(lstIndent);
}
private T GetVisualChildInDataTemplate<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChildInDataTemplate<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
VisualTreeHelper.GetChildrenCount(parent) returns 0 cause ListView is created, but not yet loaded. Particularly, the DataTemplate has not yet been applied to the ListView, consequently there is nothing in the Visual Tree.
Then use this method to get your DataGrid on Loaded event of your Window:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SeeTheChild();
}
Update:
To find a control per item in ListView:
Create a SelectionChanged event:
private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ItemContainerGenerator generator = this.listView.ItemContainerGenerator;
ListBoxItem selectedItem = (ListBoxItem)generator.ContainerFromIndex(listView.SelectedIndex);
Label aLabel = GetChildrenByType(selectedItem, typeof(Label), "label") as Label;
if (aLabel != null)
{
MessageBox.Show("We've found Label with name 'label': " + aLabel.Content);
}
else
{
MessageBox.Show("There is no such Label");
}
}
and a method which can find a necessary control for you:
public static Visual GetChildrenByType(Visual visualElement, Type typeElement, string nameElement)
{
if (visualElement == null) return null;
if (visualElement.GetType() == typeElement)
{
FrameworkElement fe = visualElement as FrameworkElement;
if (fe != null)
{
if (fe.Name == nameElement)
{
return fe;
}
}
}
Visual foundElement = null;
if (visualElement is FrameworkElement)
(visualElement as FrameworkElement).ApplyTemplate();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visualElement); i++)
{
Visual visual = VisualTreeHelper.GetChild(visualElement, i) as Visual;
foundElement = GetChildrenByType(visual, typeElement, nameElement);
if (foundElement != null)
break;
}
return foundElement;
}
So I have a FlipView defined in xaml by the following code:
<FlipView x:Name="carrousel" Height="175" Background="Transparent" Margin="0,20,0,0">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle x:Name="profile" Stroke="White" StrokeThickness="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="175" Height="175" Canvas.ZIndex="1" RadiusX="88" RadiusY="88" Tapped="profile_Tapped"/>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
When a user clicks on the rectangle, it's animated to become bigger, but I also want all the other rectangles of every other FlipViewItem to change size too. How can I achieve this? I tried:
foreach(FlipViewItem fvi in carrousel.Items)
{
Rectangle g = (fvi.Content as Grid).FindName("profile") as Rectangle;
g.Width = double;
g.Height = double;
}
But seeing as my flipview doesn't contain FlipViewItems but custom classes I've binded to it (which obviously have no .Content), it doesn't work. How can I get this to work?
foreach(var fvi in carrousel.Items)
{
FlipViewItem item=carrousel.ContainerFromItem(fvi);
var rectangle =FindElementInVisualTree<Rectangle>(item);
//Or without VisualTreeHelper you can do like what were you trying before
Rectangle g = (item.Content as Grid).FindName("profile") as Rectangle;
g.Width = double;
g.Height = double;
}
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;
}
This solution is a turn around solution (because I could not manage the relative binding).
<Grid Background="{ThemeResource SystemControlBackgroundListMediumBrush}">
<StackPanel Margin="100,10,10,10">
<FlipView x:Name="carrousel" Height="350" Width="350" Background="Red" Margin="0,20,0,0">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle x:Name="profile" Stroke="White" StrokeThickness="1" Fill="Aqua"
HorizontalAlignment="Center" VerticalAlignment="Center"
Width="{Binding ElementName=RefValueRect, Path=Width, Mode=OneWay}"
Height="{Binding ElementName=RefValueRect, Path=Height, Mode=OneWay}" Canvas.ZIndex="1" RadiusX="88"
RadiusY="88" Tapped="profile_Tapped"/>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</StackPanel>
<Rectangle x:Name="RefValueRect" Width="175" Height="175" Visibility="Collapsed" />
</Grid>
code behind
private void profile_Tapped(object sender, TappedRoutedEventArgs e)
{
RefValueRect.Width *= 2;
RefValueRect.Height *= 2;
}
my xaml code..
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="DataTemplate1" >
<Border BorderBrush="LightGray" BorderThickness="1" Height="150" Width="500" >
<Grid Width="500" Height="150" Background="White" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.9*"/>
<ColumnDefinition Width="2.5*"/>
<ColumnDefinition Width="1.5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Name="imgitem" Grid.Column="0" Height="Auto" Width="Auto" Source="{Binding ImgSource}" Margin="0,5,4,4" HorizontalAlignment="Left" />
<TextBlock x:Name="txtbindprice" Text="{Binding _PRICE,ConverterCulture=en-IN,StringFormat=C}" TextWrapping="Wrap" Grid.Column="1" Width="350" Foreground="Black" Height="60" Margin="40,70,20,-10"/>
<TextBlock x:Name="txtFinalTotal" Text="{Binding _FinalTotal}" TextWrapping="Wrap" Grid.Column="1" Width="350" Foreground="Red" Height="60" Margin="40,115,20,-10"/>
<TextBlock x:Name="txtITMNAME" Text="{Binding _ITMNAME }" Padding="1" Tap="ItmName_Tapped" TextDecorations="Underline" FontSize="24" TextWrapping="Wrap" Grid.Column="1" FontWeight="Normal" TextTrimming="WordEllipsis" Foreground="OrangeRed" Width="Auto" Height="150" Margin="30,25,10,-10"/>
<CheckBox Grid.Column="2" Grid.Row="0" Background="Black" Foreground="Black" BorderThickness="4" BorderBrush="Red" Margin="10,20,-15,10" Checked="CheckBox_Checked" Unchecked="CheckBox_UnChecked" />
</Grid>
</Border>
</DataTemplate>
<ListBox Height="Auto" Name="lstbxmanual" SelectionMode="Extended" ItemTemplate="{StaticResource DataTemplate1 }" Width="475" Margin="2,192,0,-39" Background="White" HorizontalAlignment="Left" Grid.RowSpan="2">
</ListBox>
I want to access textblocks inside listbox based on selected index
accessing textblock
string a =txtbindprice.text
wont work as they are inside data template of listbox..
I came across visual child tree methods and some other examples..i cant find much info..
please help me regarding this...
The following method finds currently selected list-box item:
private ListBoxItem FindSelectedListBoxItem(DependencyObject control)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is ListBoxItem && ((ListBoxItem)child).IsSelected)
{
// Found the control so return
return (ListBoxItem)child;
}
else
{
// Not found it - search children
ListBoxItem nextLevel = FindSelectedListBoxItem(child);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
Below method finds any child control with a certain name from a given root control:
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
return child;
}
else
{
// Not found it - search children
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
Now you can use the first method to get currently selected ListBoxItemand then pass it to the second method to retrieve any control inside this ListBoxItem (e.g. txtbindprice):
ListBoxItem item = FindSelectedListBoxItem(this);
TextBlock txtPrice = FindChildControl<TextBlock>(item , "txtbindprice") as TextBlock;
string a = txtPrice.Text;
Update
You can add SelectionChanged event to your ListBox like this:
<ListBox Height="Auto" Name="lstbxmanual" SelectionChanged="OnSelectionChanged">
</ListBox>
And then retrieve a certain TextBlock.Text (e.g. txtbindprice) this way:
public void OnSelectionChanged(object sender, SelectionChangedEventArgs args)
{
ListBoxItem item = FindSelectedListBoxItem((ListBox(sender)));
TextBlock txtPrice = FindChildControl<TextBlock>(item , "txtbindprice") as TextBlock;
string a = txtPrice.Text;
}
I am trying to find a control under my xaml in the hub control of windows phone 8.1. It may be the case my method works fine on desktop as I have testest it in wpf before but I am porting it to windows phone and may not work the same.
<Grid>
<Hub Header="Lists" Name="mainHub" >
<HubSection MinWidth="600" Name="lattestLists" Header="New Lists">
<DataTemplate>
<Grid>
<ListBox Background="Transparent" Margin="6" Height="auto" BorderThickness="2" MaxHeight="580" Grid.Row="1" x:Name="listBoxobj" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="350" >
<Border Margin="5" BorderBrush="White" BorderThickness="1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="28" Foreground="White"/>
<TextBlock Grid.Row="0" Text=">" FontSize="28" HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="White"/>
<TextBlock Margin="5,0,0,0" Grid.Row="1" x:Name="PhoneTxt" TextWrapping="Wrap" Foreground="White" FontSize="18" Text="{Binding PhoneNumber}" />
<TextBlock HorizontalAlignment="Right" Margin="0,0,35,0" Grid.Row="3" x:Name="CreateddateTxt" Foreground="White" FontSize="18" TextWrapping="Wrap" Text="{Binding CreationDate}" />
</Grid>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</HubSection>
<HubSection Header="Tech" IsHeaderInteractive="True"
Background="#222222" MinWidth="250">
<DataTemplate>
<StackPanel>
<TextBlock Text="Tech news goes here."
Style="{ThemeResource BodyTextBlockStyle}" />
<TextBlock Text="Click the header to go to the Tech page."
Style="{ThemeResource BodyTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</HubSection>
<HubSection Header="Sports" IsHeaderInteractive="True"
Background="#444444" MinWidth="250">
<DataTemplate>
<StackPanel>
<TextBlock Text="Sports news goes here."
Style="{ThemeResource BodyTextBlockStyle}" />
<TextBlock Text="Click the header to go to the Sports page."
Style="{ThemeResource BodyTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</HubSection>
</Hub>
</Grid>
I am trying to use the following method to find the lsitbox but its not working
ListBox listBoxobjc = FindChildControl<ListBox>(this, "listBoxobj") as ListBox;
listBoxobjc.ItemsSource = DB_ContactList.OrderByDescending(i => i.id).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
This is the method FindChildControl
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
return child;
}
else
{
// Not found it - search children
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
Edit
I debuged the code and its showing the control as null even though I have done the same way as i would
I have replace my method to find children a couple of times during the different versions of Windows Phone / Windows Runtime with this one being the most reliable. Just in case you're not able to spot the mistake you could also try this one and see if it yields better results:
public T FindElementByName<T>(DependencyObject element, string sChildName) where T : FrameworkElement
{
T childElement = null;
var nChildCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < nChildCount; i++)
{
FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
if (child == null)
continue;
if (child is T && child.Name.Equals(sChildName))
{
childElement = (T)child;
break;
}
childElement = FindElementByName<T>(child, sChildName);
if (childElement != null)
break;
}
return childElement;
}
Also when using this method shortly after creating / loading content I call UpdateLayout beforehand:
this.UpdateLayout();
But be careful - this is not one of the performance-friendliest methods (see also: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.updatelayout).