Combobox SelectedItem is not working in UWP - c#

I have a Combobox with some items, i fill combobox this way:
var files = Directory.GetFiles(Constants.TranslationsPath);
var items = new ObservableCollection<Translation>();
using var db = new AlAnvarDBContext();
if (files.Count() > 0)
{
foreach (var file in files)
{
var id = Path.GetFileNameWithoutExtension(file);
var trans = db.Translations.Where(x => x.Link.Contains(id)).FirstOrDefault();
if (trans != null)
{
items.Add(trans);
}
}
cmbTranslators.ItemsSource = items;
cmbTranslators.SelectedItem = Settings.DefaultTranslation;
}
and xaml:
<ComboBox x:Name="cmbTranslators">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="table:Translation">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind Name}"/>
<TextBlock Text="-"/>
<TextBlock Text="{x:Bind Language}"/>
<TextBlock Text="-"/>
<TextBlock Text="{x:Bind Translator}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The problem is that the default item (SelectedItem) is not selected and i need to select default item in combobox.

cmbTranslators.SelectedItem = cmbTranslators.Items.Where(x=>((Translation)x).Id == Settings.DefaultTranslation.Id).FirstOrDefault();

Is it possible that the Settings.DefaultTranslation is not equal to any of the items in the item collection and that is why the assignment did not occur? Maybe you can add it to your collection Settings.DefaultTranslation like the first element and set cmbTranslators.SelectedIndex = 0

Related

How to get controls inside Pivot.ItemTemplate in Pivot in UWP?

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.

send the content of a ListviewItem to a TextBlock

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;

cascading dropdown in wp8

I'm try to create cascading dropdown when i select first one it's working fine.On SelectionChanged i'm try to bind second drop down on code behind it's show the result fine.But Dropdown show empty.here is my code..
Location ld = new Location();
ld = categoryList.SelectedItem as Location;
string id = "0";
try
{
id = Convert.ToString(ld.id);
}
catch (Exception ex)
{ }
if (id != "0")
{
// lstSublocation.Visibility = Visibility.Visible;
var lst = _lstlocation.Where(z => z.id == id).Select(z => z.sub_location).ToList();
lstSublocation.ItemsSource = lst;
}
In lst show 2 items.
<toolkit:ListPicker x:Name="lstSublocation" Foreground="Black"
BorderThickness="2" SelectionMode="Single"
VerticalAlignment="Bottom" Margin="12,0,10,460" BorderBrush="LightGray" Height="68" >
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}" Margin="12 0 0 0" Foreground="Black"/>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0 21 0 20">
<TextBlock Text="{Binding name}"
Foreground="Black"
/>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>
Here is front end code ..... :( 2 hours struggle with this code like wrestlemania fight... :)
Code should work (as posted), this is probably where the problem is
var lst = _lstlocation.Where(z => z.id == id).Select(z => z.sub_location).ToList();
lstSublocation.ItemsSource = lst;
Put a break point at lstSublocation.ItemsSource = lst; and check what lst is
Make sure it's actually a List<your_model> and that your_model has a Property of name not just a public variable.. like this
public class sample_model
{
public sample_model()
{
this.name = "default";
}
public string name { get; set; } // this is bindable
// public string name; // this is NOT bindable
}

get checked items of listview using checkbox windows store app c#

I am developing one Windows store application. I have implemented one listview. listview contains image , textblock and checkbox controls. my listview gets the data from internet i have done xml parsing with listview and binded data to listview. i want to get all the data from listview where checkboxes are checked in listview.
my xaml code is:
<ListView Name="display" ItemsSource="{Binding}" SelectionMode="Single"
SelectionChanged="display_SelectionChanged"
ScrollViewer.HorizontalScrollMode="Enabled" ScrollViewer.HorizontalScrollBarVisibility="Visible"
ItemContainerStyle="{StaticResource ListViewItemStyle12}" >
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel x:Name="stak2" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Image Source="{Binding Path=Image}" Width="450" Tapped="image_taped" />
<CheckBox Tag="{Binding Path=tag}" Visibility="{Binding Path=visichk}" Height="40" Name="addremove"
HorizontalAlignment="Center" Checked="add_checked" Unchecked="sub_checked" Opacity="0.5"
Background="White" VerticalAlignment="Top" Template="{StaticResource CheckboxImageTemplate}" >
</CheckBox>
<TextBlock Text="{Binding Image_code}" FontSize="25" Foreground="Gray" HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
datasource for listview :
XDocument xmlDoc = XDocument.Parse(responseString);
var Categories = xmlDoc.Descendants("product").ToArray();
List<ProductData> displaylst = new List<ProductData>(); //ProductData is my Class.
foreach (var cat in Categories)
{
string prId = cat.Elements("id_products").Select(r => r.Value).FirstOrDefault();
List<string> Image = cat.Descendants("images").Elements("src").Attributes("largimage").Select(r => r.Value).ToList();
List<string> Image_code = cat.Descendants("images").Elements("src").Select(r => r.LastAttribute.Value).ToList();
int i = 0;
foreach (string img in Image)
{
displaylst.Add(new ProductData { Id = prId, Image = img, Image_code = Image_code[i] });
i++;
}
}
display.ItemsSource = displaylst;
Now on one button click i want to get the data of Product like prId,Image,Image_code where checkbox are checked from listview and put it into the simple list.
how can i did this please help me. thanks in advance.
First let's add a property to your ProductData class
public class ProductData
{
public string Id { get; set; }
public string Image { get; set; }
// I dont know exactly what's in this class
// ... more properties
// Add this one
public bool IsSelected { get; set; }
}
Now that we have a boolean IsSelected in our ProductData class we can know which are selected.
In the second foreach change this line
// Set IsSelected to false by default
displaylst.Add(new ProductData { IsSelected = false, Id = prId, Image = img, Image_code = Image_code[i] });
And bind the "IsChecked" property of your checkbox to IsSelected
<CheckBox IsChecked="{Binding Path=IsSelected}" Tag="{Binding Path=tag}" Visibility="{Binding Path=visichk}" Height="40" Name="addremove"
HorizontalAlignment="Center" Checked="add_checked" Unchecked="sub_checked" Opacity="0.5"
Background="White" VerticalAlignment="Top" Template="{StaticResource CheckboxImageTemplate}" >
With binding when you check one of the checkbox, the associed productData IsSelected property will become "true" automatically.
So now you just have to do a new list and select only ProductData where IsSelected is true:
List<ProductData> listOfSelectedProducts = (from product in displaylst
where product.IsSelected == true
select product).ToList();
Here you go you got a list of ProductData with only selected products.

binding data - inotifypropertychanged does not work

I have a listBox1 in which data are binding from the list. Then I want to when I select any item from listBox1 in listBox2 will binding data from another list.
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Teams teams = (Teams)listBox1.SelectedItems[0];
getH2hResults("//td[#class='hell']", teams.Team1, teams.Team2); // add elements to list
getH2hResults("//td[#class='dunkel']", teams.Team1, teams.Team2); // and here also
listBox2.ItemsSource = lists.h2hList;
}
On the first time this work, but for the twice time listBox2 doesn't displays new data.
public class Lists : BindableBase
{
public Lists()
{
_teamsList = new List<Teams>();
_h2hList = new List<H2H>();
}
private List<Teams> _teamsList;
public List<Teams> teamsList
{
get
{
return _teamsList;
}
set
{
if (value != _teamsList)
{
_teamsList = value;
RaisePropertyChanged("teamsList");
}
}
}
private List<H2H> _h2hList;
public List<H2H> h2hList
{
get
{
return _h2hList;
}
set
{
if (value != _h2hList)
{
_h2hList = value;
RaisePropertyChanged("h2hList");
}
}
}
}
And XAML
<ListBox Name="listBox1" Width="300" Height="300"
VerticalAlignment="Top"
HorizontalAlignment="Left"
ItemsSource="{Binding teamsList}" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="#FF4273CD" Text="{Binding Team1, Mode=TwoWay}"></TextBlock>
<TextBlock Text=" vs " FontWeight="Bold"></TextBlock>
<TextBlock Foreground="#FF4273CD" Text="{Binding Team2, Mode=TwoWay}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Name="listBox2" Grid.Column="1" Width="300" Height="300"
VerticalAlignment="Top"
HorizontalAlignment="Left"
ItemsSource="{Binding h2hList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding date, Mode=TwoWay}"></TextBlock>
<TextBlock Text="{Binding result, Mode=TwoWay}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
RaisePropertyChanged("teamList");
is Wrong your propery is named 'teamsList' with an S,
change to:
RaisePropertyChanged("teamsList");
It is the public property you bind to and notify changes of,
edit:
also change your binding:
ItemsSource="{Binding teamList}"
to
ItemsSource="{Binding teamsList}"
Edit 2:
listBox2.DataContext = xxx
Not itemsource = xxx
With the line (in listBox1_SelectionChanged)
listBox2.ItemsSource = lists.h2hList;
you are effectively removing the binding from the ItemsSource property of listBox2.
Instead, you should only update the h2hList property in your Lists class (which presumably happens in getH2hResults) and remove the above line from your code.
Note however that it is not sufficient to clear and re-fill that list. You need to set the h2hList property in order to get a property change notification raised:
var newList = new List<H2H>();
// fill newList before assigning to h2hList property
lists.h2hList = newList;
If you want to keep the list and just change its elements, you would need to use ObservableCollection<H2H> instead of List<H2H> as collection type. This would be the better approach anyway, as you would not have to care for when exactly you add elements to a newly created collection.

Categories

Resources