I need to create a new ListBox based on items that are selected (checked). The following code actually worked if I only had like 20 items on the ListBox, but adding more items make it crash. Can anybody know how to make it work, or have a different aproach? Is there a limite for looping through a listBox?
// worked fine for 20 items,
// but my actual list contems 95 items...
private void btnCreateNewList_Click(object sender, RoutedEventArgs e)
{
int totalItemsCB = ListCheckBoxVocabulary.Items.Count;
for (int ii = 0; ii < totalItemsCB-1; ii++)
{
ListBoxItem item = this.ListCheckBoxVocabulary.ItemContainerGenerator.ContainerFromIndex(ii) as ListBoxItem;
CheckBox thisCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
if (thisCheckBox.IsChecked == true)
{
dataPlayListSource.Add(new SampleData() { Text = thisCheckBox.Content.ToString() + " | " + ii });
// this.PlayListCheckBoxVocabulary.UpdateLayout();
this.PlayListCheckBoxVocabulary.ItemsSource = dataPlayListSource;
}
}
}
private T FindFirstElementInVisualTree<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 = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
and xaml:
<controls:PivotItem Header="Vocabulary" >
<ListBox x:Name="ListCheckBoxVocabulary" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<!--<StackPanel Margin="0,0,0,17" Width="432">-->
<CheckBox x:Name="cbVocabulary" Content="{Binding Text}" Checked="CheckBox_Checked" Unchecked="UncheckBox" />
<!--</StackPanel>-->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PivotItem>
The list is virtual - controls are created as they are needed and potentially reused (I think).
Your options are to turn the ListBox to not be virtualized (override the template, and for the container, instead of a SerializedStackPanel, choose a regular StackPanel).
Your other (and preferable) option is to do the checking via Data Binding. Way easier and faster in most situations.
Related
I have this XAML that displays 6 TextCells which can show a check mark or not. They also so as enabled or not enabled:
<TableSection Title="Front Side" x:Name="cfsSection">
<local:CustomTextCell Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" IsEnabled="{Binding [0].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
<local:CustomTextCell Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" IsEnabled="{Binding [1].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
<local:CustomTextCell Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" IsEnabled="{Binding [2].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
<local:CustomTextCell Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" IsEnabled="{Binding [3].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
<local:CustomTextCell Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" IsEnabled="{Binding [4].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
<local:CustomTextCell Text="{Binding [5].Name}" IsChecked="{Binding [5].IsSelected}" IsEnabled="{Binding [5].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
</TableSection>
The code behind is I think fairly simple. It declares an array of SSVViewModel and the binding causes the text to display:
SSVViewModel[] CFS = new[] {
new SSVViewModel {Id = 0, Name=LANG.English.Text(), IsSelected = false},
new SSVViewModel {Id = 1, Name=LANG.Romaji.Text(), IsSelected = false},
new SSVViewModel {Id = 2, Name=LANG.Kana.Text(), IsSelected = false},
new SSVViewModel {Id = 3, Name=LANG.Kanji.Text(), IsSelected = false},
new SSVViewModel {Id = 4, Name=LANG.KanjiKana.Text(), IsSelected = false},
new SSVViewModel {Id = 5, Name=LANG.KanaKanji.Text(), IsSelected = false},
};
When a cell is clicked this function is called:
void cfsSelectValue(object sender, EventArgs e)
{
var cell = sender as TextCell;
if (cell == null)
return;
var selected = cell.Text;
foreach (var setting in CFS)
setting.IsSelected = false;
foreach (var setting in CFS)
if (setting.Name == selected)
setting.IsSelected = true;
}
However when clicking on either of the first two cells both show as checked. All other cell clicks work fine. In another part of my code I use a similar construct and it's the last two cells that do not work.
Note that the IsEnabled works but not the IsChecked
Can anyone see why a click on the first two cells could possibly give any problem. I have been through this with the debugger many time but I still cannot see what might be wrong. Surely the code that sets the IsSelected to false should cause all except the one cell to show as checked.
Note that when debugging this line: setting.IsSelected = false; and this line: setting.IsSelected = true; then everything appears as it should as the correct cell has it's IsSelected set to true and the others to false. It's just when I look at the display it seems like the binding didn't work for those first two cells.
Here's the viewModel code I am using:
public class SSVViewModel: ObservableProperty
{
private int id;
private string name;
private bool isSelected;
public int Id
{
get
{
return id;
}
set
{
if (value != id)
{
id = value;
NotifyPropertyChanged("Id");
}
}
}
public string Name
{
get
{
return name;
}
set
{
if (value != name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
public bool IsSelected
{
get
{
return isSelected;
}
set
{
if (value != isSelected)
{
isSelected = value;
NotifyPropertyChanged("IsSelected");
}
}
}
}
Here is the code for the CustomTextCellRenderer
public class CustomTextCellRenderer : TextCellRenderer
{
UITableViewCell _nativeCell;
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
_nativeCell = base.GetCell(item, reusableCell, tv);
var formsCell = item as CustomTextCell;
if (formsCell != null)
{
formsCell.PropertyChanged -= OnPropertyChanged;
formsCell.PropertyChanged += OnPropertyChanged;
}
SetCheckmark(formsCell);
SetTap(formsCell);
return _nativeCell;
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var formsCell = sender as CustomTextCell;
if (formsCell == null)
return;
if (e.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
{
SetCheckmark(formsCell);
}
if (e.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
{
SetTap(formsCell);
}
}
private void SetCheckmark(CustomTextCell formsCell)
{
if (formsCell.IsChecked)
_nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
else
_nativeCell.Accessory = UITableViewCellAccessory.None;
}
private void SetTap(CustomTextCell formsCell)
{
if (formsCell.NoTap)
_nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
else
_nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
}
}
Update 1
<local:CustomTextCell Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" Tapped="cfsSelectValue" CommandParameter="0" />
<local:CustomTextCell Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" Tapped="cfsSelectValue" CommandParameter="1" />
<local:CustomTextCell Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" Tapped="cfsSelectValue" CommandParameter="2" />
<local:CustomTextCell Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" Tapped="cfsSelectValue" CommandParameter="3" />
<local:CustomTextCell Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" Tapped="cfsSelectValue" CommandParameter="4" />
Since the question was written I have stopped using this for the Lang selection however it's still used in another part of the code and I tried to put in some debug points. Here's what I did:
I added this to the iOS custom renderer:
private void SetCheckmark(CustomTextCell formsCell)
{
if (formsCell.IsChecked)
{
_nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
Debug.WriteLine(_nativeCell.TextLabel.Text + " checked");
}
else
{
_nativeCell.Accessory = UITableViewCellAccessory.None;
Debug.WriteLine(_nativeCell.TextLabel.Text + " unchecked");
}
}
Here's the result when I clicked JLPT N2:
Category Group unchecked
Category unchecked
All Available Words unchecked
Japanese for Busy People 1 unchecked
Japanese for Busy People 2 unchecked
Japanese for Busy People 3 unchecked
JLPT Level N5 unchecked
JLPT Level N4 unchecked
JLPT Level N3 unchecked
JLPT Level N2 unchecked
JLPT Level N1 checked
JLPT Level N2 checked
JLPT Level N3 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
This was not at all what I expected.
On the screen I see that as expected N2 is disabled but there is a check mark next to N3 and N2.
Not sure if this helps but I notice the iOS renderer code used is different from similar code I have used in other places. For example here's a different iOS renderer. Code looks very different. I realize function is different but this one has things like cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;
public class TextCellCustomRenderer : TextCellRenderer
{
CellTableViewCell cell;
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var textCell = (TextCell)item;
var fullName = item.GetType().FullName;
cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;
if (cell == null)
{
cell = new CellTableViewCell(UITableViewCellStyle.Value1, fullName);
}
else
{
cell.Cell.PropertyChanged -= cell.HandlePropertyChanged;
//cell.Cell.PropertyChanged -= Current_PropertyChanged;
}
cell.Cell = textCell;
textCell.PropertyChanged += cell.HandlePropertyChanged;
cell.PropertyChanged = this.HandlePropertyChanged;
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
cell.TextLabel.Text = textCell.Text;
cell.DetailTextLabel.Text = textCell.Detail;
cell.ContentView.BackgroundColor = UIColor.White;
switch (item.StyleId)
{
case "checkmark":
cell.Accessory = UIKit.UITableViewCellAccessory.Checkmark;
break;
case "detail-button":
cell.Accessory = UIKit.UITableViewCellAccessory.DetailButton;
break;
case "detail-disclosure-button":
cell.Accessory = UIKit.UITableViewCellAccessory.DetailDisclosureButton;
break;
case "disclosure":
cell.Accessory = UIKit.UITableViewCellAccessory.DisclosureIndicator;
break;
case "none":
default:
cell.Accessory = UIKit.UITableViewCellAccessory.None;
break;
}
//UpdateBackground(cell, item);
return cell;
}
void checkAccessoryVisibility() {
}
}
As per the log statements, it looks like the unsubscribe logic for property-changed-handler is not working as expected.
With TextCellRenderer, we don't need to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.
Changing the renderer code to use this method (similar to this answer) should hopefully resolve this problem:
public class CustomTextCellRenderer : TextCellRenderer
{
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
if (item is CustomTextCell formsCell)
{
SetCheckmark(nativeCell, formsCell);
SetTap(nativeCell, formsCell);
}
return nativeCell;
}
protected override void HandlePropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.HandlePropertyChanged(sender, args);
System.Diagnostics.Debug.WriteLine($"HandlePropertyChanged {args.PropertyName}");
var nativeCell = sender as CellTableViewCell;
if (nativeCell?.Element is CustomTextCell formsCell)
{
if (args.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
SetCheckmark(nativeCell, formsCell);
else if (args.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
SetTap(nativeCell, formsCell);
}
}
void SetCheckmark(UITableViewCell nativeCell, CustomTextCell formsCell)
{
if (formsCell.IsChecked)
nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
else
nativeCell.Accessory = UITableViewCellAccessory.None;
}
void SetTap(UITableViewCell nativeCell, CustomTextCell formsCell)
{
if (formsCell.NoTap)
_nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
else
_nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
}
}
I could not find the error causing that behaviour so here are my thoughts on this:
The behaviour you are describing sounds more like a RadioButton. Since there are none in Xamarin.Forms you could create your own, use a package or get a workaround.
Most easy workaround would be in your cfsSelectValue.
You could search the visual tree for all elements of local:CustomTextCells and set IsSelected to false for each TextCell that is not the one passed as the sender.
How I would do it:
Things to try out:
For your ViewModels use an ObservableCollection rather than an Array
private ObservableCollection<SSVViewModel> viewModels = new ObservableCollection<SSVViewModel>()
{
new SSVViewModel {Id = 0, Name=LANG.English.Text()},
new SSVViewModel {Id = 1, Name=LANG.Romaji.Text()},
new SSVViewModel {Id = 2, Name=LANG.Kana.Text()},
new SSVViewModel {Id = 3, Name=LANG.Kanji.Text()},
new SSVViewModel {Id = 4, Name=LANG.KanjiKana.Text()},
new SSVViewModel {Id = 5, Name=LANG.KanaKanji.Text()},
};
Derive your ViewModel from INotifyPropertyChanged rather than ObservableProperty
public class SSVViewModel : INotifyPropertyChanged
{
private int id;
private string name;
private bool isSelected = false; //Set the default here
public int Id
{
get
{
return id;
}
set
{
if (value != id)
{
id = value;
OnPropertyChanged();
}
}
}
public string Name
{
get
{
return name;
}
set
{
if (value != name)
{
name = value;
OnPropertyChanged();
}
}
}
public bool IsSelected
{
get
{
return isSelected;
}
set
{
if (value != isSelected)
{
isSelected = value;
OnPropertyChanged();
}
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyname = null)
{
if(PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyname));
}
}
#endregion
}
Change your cfsSelectValue to this:
public void cfsSelectValue(object sender, EventArgs e)
{
//GetCurrentCell
CustomTextCell cell = sender as CustomTextCell;
if (cell == null)
{
return;
}
foreach (SSVViewModel viewModel in CFS)
{
/*
Since there is no Tag Property we gotta use something different
you could use `CommandParameter` since it is of type object
*/
if (viewModel.Name == cell.Text && viewModel.Id == int.Parse(cell.CommandParameter.ToString()))
{
viewModel.IsSelected = true;
}
else
{
viewModel.IsSelected = false;
}
}
}
The code looks right to me - the only reason I would imagine this happening is in case the string comparison logic is not working as expected.
Maybe a reference based comparison might solve the issue. i.e Change your XAML to:
<TableSection Title="Front Side" x:Name="cfsSection">
<local:CustomTextCell BindingContext="{Binding [0]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
<local:CustomTextCell BindingContext="{Binding [1]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
<local:CustomTextCell BindingContext="{Binding [2]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
<local:CustomTextCell BindingContext="{Binding [3]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
<local:CustomTextCell BindingContext="{Binding [4]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
<local:CustomTextCell BindingContext="{Binding [5]}" Text="{Binding Name}" IsChecked="{Binding IsSelected}" Tapped="cfsSelectValue"/>
</TableSection>
and tapped handler to:
void cfsSelectValue(object sender, EventArgs e)
{
var cell = sender as TextCell;
if (cell == null)
return;
var selected = cell.BindingContext;
foreach (var setting in CFS)
setting.IsSelected = (setting == selected);
}
How can I add many Button to the grid for the first Item and and textbox to another grid in the second item dynamically?
NOT XAML
Ican't find name GridItem - name not exist in code behind :(
I tried to find Visual Tree Helper :(
PivotItem pivotVHT = (PivotItem)mainSecondPivot.SelectedItem;
foreach (var element in VisualTreeHelper.FindElementsInHostCoordinates(new Rect(20, 0, 480, 700), pivotVHT))
{
if (element is TextBlock)
{
Debug.WriteLine("{0}", ((TextBlock)element).Text);
TextBlock test = ((TextBlock)element);
test.Text = "TEST";
}
}
VisualTreeHelper changing the text only mainFirstPivot, visual tree helper does not see mainSecondPivot
XAML:
<controls:Pivot Title="Photo Gallery" Name="mainSecondPivot" >
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<Grid
x:Name="PivitGrid"
>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Image
Name="PivotImageGalery"
Source="{Binding imgSrc}"
>
</Image>
<TextBlock
x:Name="TextBlockPivot"
Text="{Binding textBlockPivotName}"
>
</TextBlock>
</Grid>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ScrollViewer
Name="SVName"
Width="Auto"
VerticalScrollBarVisibility ="Hidden"
HorizontalScrollBarVisibility="Disabled"
>
<Grid
x:Name="GridItem"
>
**HERE**
</Grid>
</ScrollViewer>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
C#
public static class SelectedIndex
{
public static int SelectedIndexInt = 0;// OR SOME NUMBER
}
public class IListPivot
{
public ImageSource imgSrc { get; set; }
public String textBlockPivotName { get; set; }
}
public secondPage()
{
InitializeComponent();
IList<IListPivot> PivotList = new List<IListPivot>();
for (z = 0; z <= 7; z++)
{
PivotList.Add(new IListPivot()
{
imgSrc = new System.Windows.Media.Imaging.BitmapImage(new Uri("URI", UriKind.Relative)),
textBlockPivotName = "TEXT"
});
}
mainSecondPivot.ItemsSource = PivotList;
mainSecondPivot.Loaded += new RoutedEventHandler (PivotLoaded);
mainSecondPivot.SelectedIndex = SelectedIndex.SelectedIndexInt
}
public void PivotLoaded(object sender, EventArgs e)
{
PivotItem pivotItemVHT = (PivotItem)mainSecondPivot.ItemContainerGenerator.ContainerFromIndex(SelectedIndex.SelectedIndexInt);
var root = VisualTreeHelper.GetChild(((VisualTreeHelper.GetChild(pivotItemVHT, 0) as Grid).Children[0] as ContentPresenter), 0) as FrameworkElement;
Debug.WriteLine(" root " + root);
Debug.WriteLine(" root Name " + root.Name);
ScrollViewer scr = (ScrollViewer)root;
TextBox BoxText1 = new TextBox();
BoxText1.Text = a.ToString();
scr.Content = BoxText1;
}
add only to one from everyone items
HELP
Here is how to retrieve a named element from inside a PivotItem:
public FrameworkElement GetPivotElement(int pivotIndex, string name)
{
var pivot = mainSecondPivot.ItemContainerGenerator.ContainerFromIndex(pivotIndex);
var root = VisualTreeHelper.GetChild(((VisualTreeHelper.GetChild(pivot, 0) as Grid).Children[0] as ContentPresenter), 0) as FrameworkElement;
return root.FindName(name);
}
I filled the icBoard with 50 Cell objects, so each Rectangle object has Cell as data object. Now, I want according to index or cell object to get the corresponding Rectangle element. For example I want to get the Rectangle in index=15. Not it's data but the Rectangle itself.
How I can do this?
public MainPage()
{
InitializeComponent();
var cells = new List<Cell>();
for (int i = 0; i < 50; i++)
{
cells.Add(new Cell());
}
icCells.ItemsSource = cells;
}
public void sector_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
//some code
//....
var tappedRectangle = (sender as Rectangle);
var spesificRectangle = SOMEHOW_GET_RECTANGLE_AT_POSITION_15;
}
<ItemsControl Name="icBoard" Grid.Column="0" Margin="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Fill="#501e4696" Width="30" Height="30" Margin="1" Tap="sector_Tap" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
I believe this might work:
ContentPresenter contentPresenter = itemsControl.ItemContainerGenerator.ContainerFromIndex(15) as ContentPresenter;
Rectangle rectangle= FindVisualChild<Rectangle>(contentPresenter );
if (rectangle != null)
{
}
public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
<ListBox Name="listBoxButtons"
Height="700">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="{StaticResource PhoneAccentBrush}"
Name="border"
Width="432" Height="62"
Margin="6" Padding="12,0,0,6">
<TextBlock Text="{Binding}"
Foreground="#FFFFFF" FontSize="26.667"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
<Border.Projection>
<PlaneProjection RotationX="-60"/>
</Border.Projection>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code:
private void ShowAnim()
{
IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
Storyboard _swivelShow = new Storyboard();
foreach (var item in this.listBoxButtons.Items)
{
UIElement container = listBoxButtons.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
if (container != null)
{
Border content = VisualTreeHelper.GetChild(container, 0) as Border;
if (content != null)
{
DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
showKeyFrame1.Value = -60;
showKeyFrame1.EasingFunction = quadraticEase;
EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(85);
showKeyFrame2.Value = 0;
showKeyFrame2.EasingFunction = quadraticEase;
showAnimation.KeyFrames.Add(showKeyFrame1);
showAnimation.KeyFrames.Add(showKeyFrame2);
Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
Storyboard.SetTarget(showAnimation, content.Projection);
_swivelShow.Children.Add(showAnimation);
}
}
}
_swivelShow.Begin();
}
But: Storyboard.SetTarget(showAnimation, content.Projection) throws an Exception. The content.Projection is null. How could that happen?
You are looking at the wrong Border element. The hierarchy of the item container in your case is like Border -> ContentControl -> ContentPresenter -> Border (this is yours). So you have to go deeper down the child hierarchy of your container to find the border you want.
The following code searches the children of an UIElement recursively and gives some debug output so you can see how deep it goes. It will stop when it finds a control named "border":
private UIElement GetMyBorder(UIElement container)
{
if (container is FrameworkElement && ((FrameworkElement)container).Name == "border")
return container;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(container); i++)
{
var child = (FrameworkElement)VisualTreeHelper.GetChild(container, i);
System.Diagnostics.Debug.WriteLine("Found child "+ child.ToString());
System.Diagnostics.Debug.WriteLine("Going one level deeper...");
UIElement foundElement = GetMyBorder(child);
if (foundElement != null)
return foundElement;
}
return null;
}
To use it:
Border content = (Border)GetMyBorder(container);
It's very simple task, but I struggle for hours.
I have parse xml from web sources and bind them to listbox. Now I want to make an index for each items binded to list box, something like this:
1.Title 2.Title 3.Title
Author Author Author
Date Date Date
Here is what I have so far:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="stkPnl" Orientation="Horizontal" Margin="15,0" MouseEnter="stkPnl_MouseEnter" MouseLeave="stkPnl_MouseLeave">
<Image x:Name="imageAV" Source="{Binding avlink}" Height="80" Width="80"
Stretch="UniformToFill" MouseLeftButtonUp="imageAV_MouseLeftButtonUp" ImageFailed="imageAV_ImageFailed"/>
<StackPanel Orientation="Vertical" Margin="10,0,0,0" MouseLeftButtonUp="StackPanel_MouseLeftButtonUp">
<TextBlock Text="{Binding nickname}" Width="Auto" />
<TextBlock Text="{Binding track}" FontWeight="Bold" Width="Auto"/>
<TextBlock Text="{Binding artist}" Width="Auto"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
and MainPage.xaml.cs
private void DoWebClient()
{
var webClient = new WebClient();
webClient.OpenReadAsync(new Uri("http://music.mobion.vn/api/v1/music/userstop?devid="));
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (var reader = new StreamReader(e.Result))
{
string s = reader.ReadToEnd();
Stream str = e.Result;
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("user")
select new mobion
{
avlink = (string)query.Element("user_info").Element("avlink"),
nickname = (string)query.Element("user_info").Element("nickname"),
track = (string)query.Element("track"),
artist = (string)query.Element("artist"),
};
listBox.ItemsSource = data;
}
}
As you see I only have nickname, track and artist, if I want to add an index that increase for each listboxItem, how can I do that?
Thank you for reading this question.
I know it's ugly, but it's an idea: Create a wrapper class for around your mobion class:
public class mobionWrapper : mobion
{
public int Index { get; set; }
}
Instead of selecting mobion instances you select mobionWrapper instances:
var data = from query in xdoc.Descendants("user")
select new mobionWrapper
{
avlink = (string)query.Element("user_info").Element("avlink"),
nickname = (string)query.Element("user_info").Element("nickname"),
track = (string)query.Element("track"),
artist = (string)query.Element("artist"),
};
After binding the your data, set the Index property of your wrapper class:
listBox.ItemsSource = data;
for(int i = 0; i < listBox.Items.Count; i++)
{
var item = listBox.Items[i] as mobionWrapper;
item.Index = i + 1;
}
Now you need a new TextBlock and bind it to the Index property:
<TextBlock Text="{Binding Index}" Width="Auto" />
Worked for me. Keep in mind that the index might be invalid after sorting or filtering the data display.
Assuming you've an appropriate field in you mobion class (which you can bind to in the view), you can use an incrementing counter to populate this field as the document is iterated over.
int[] counter = { 1 };
var data = from query in xdoc.Descendants("user")
select new mobion
{
index = counter[0]++,
avlink = (string)query.Element("user_info").Element("avlink"),
nickname = (string)query.Element("user_info").Element("nickname"),
track = (string)query.Element("track"),
artist = (string)query.Element("artist"),
};
Note that counter is an array of int rather than just an int to prevent accessing a modified closure.