TextCellRenderer in Xamarin.UWP - xamarin

How could we set TextCell height with padding/margin in Windows Universal Project using Xamarin.Forms?
I tried following Custom renderer in Native project:
class CustomTextCellRenderer : TextCellRenderer
{
public override Windows.UI.Xaml.DataTemplate GetTemplate(Cell cell)
{
var d = base.GetTemplate(cell);
//Set something here???
return d;
}
}
but couldn't find any property to be set.
There is function to set dependency property of DataTemplate but I coudn't figure it out, what will be the dependency property name for height to set?
d.SetValue(???DependencyProperty???, value);

Since the TextCell is a built in cell, it's optimized and designed to be used as is. However you can create a custom DataTemplate based on the TextCell template and return that instead.
You can find the original template in the Xamarin.Forms source. Then in the UWP platform project's App.xaml, define your new DataTemplate inside the ResourceDictionary with a different key:
<DataTemplate x:Key="MyTextCell">
<StackPanel Background="Aqua">
<TextBlock
Padding="0 10 0 10"
Margin="5"
Text="{Binding Text}"
Style="{ThemeResource BaseTextBlockStyle}" />
<TextBlock
Text="{Binding Detail}"
Style="{ThemeResource BodyTextBlockStyle}"
x:Name="detail"/>
</StackPanel>
</DataTemplate>
and access it inside the custom renderer with:
return App.Current.Resources["MyTextCell"] as Windows.UI.Xaml.DataTemplate;

Related

How to implement Carousel View in Xamarin.forms

Is there any way we can create Carousel View instead of Carousel page so that only portion of the page swipes left or right. Also I want to create this control in the Xamarin Forms and not specific to platform.
If we need to create this custom control in the xamarin.android or xamarin.iOS then what is the real benefits of using the Xamarin.forms where this simple requirements are not getting satisfied.
There's a well documented CarouselView project hosted on github:
https://github.com/chrisriesgo/xamarin-forms-carouselview
and
http://chrisriesgo.com/xamarin-forms-carousel-view-recipe/
The nuget package for the CarouselView is now available (v2.3.0-pre1):
https://www.nuget.org/packages/Xamarin.Forms.CarouselView/2.3.0-pre1
We can use the CarouselView which was introduced in Xamarin forms 4.3. Now in Xamarin 4.6, we don't have to use the Forms.SetFlags("CollectionView_Experimental"); in appdelegate of iOS and mainactivity of android.
However, to use the indicatorview for the Carousel page we have to set this
Forms.SetFlags("IndicatorView_Experimental"); in appdelegate of iOS and mainactivity of android.
I have just implemented a similar thing. To create the a carousel view, I just created a horizontal Stacklayout, wrapped in a horizontal scroll view.
In my particular example, I needed to create an image gallery. I used the Camera control from the Xamarin.Labs project to get the image from either the camera roll or the camera itself. I then added this as a child to the Stacklayout.
Hope this helps.
As of Xamarin.Forms V2.2.0-pre1 CarouselView has now been added to Xamarin.Forms.
CarouselView
CarouselView is intended to fully replace CarouselPage. CarouselPage
will be deprecated in a future release. CarouselView is superior in
many ways, including its ability to be virtualized and nested within
layouts.
See https://forums.xamarin.com/discussion/63983/xamarin-forms-2-2-0-pre1-released#latest
Unfortunately there is no documentation on this as of yet.
EDIT:
CarouselView was Removed for Xamarin.Forms V2.2.0.31 because it wasn't ready for stable release. But from the look of it it will be merged back soon.
For now you can find the seperate CarouselView nuget package here: https://www.nuget.org/packages/Xamarin.Forms.CarouselView/2.3.0-pre1
and you can use it like so:
Namespace:
xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
Then we can simply add the CarouselView at the top of our page:
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height=".3*"/>
<RowDefinition Height=".7*"/>
</Grid.RowDefinitions>
<cv:CarouselView ItemsSource="{Binding Zoos}" x:Name="CarouselZoos">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl}"/>
<StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
<Label TextColor="White" Text="{Binding Name}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</Grid>
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
<!--List of Monkeys below-->
</Grid>
more info: https://blog.xamarin.com/flip-through-items-with-xamarin-forms-carouselview/
If you use Xamarin.Forms V2.2.0-pre1 and you need to display different views for each page, you can use a derived class like that:
public class CarouselViewMultiPage : CarouselView
{
List<View> _children = new List<View> { };
public List<View> Children {
get { return _children; }
set {
_children = value;
OnPropertyChanged();
}
}
public CarouselViewMultiPage ()
{
this.ItemTemplate = new CarouselTemplateSelector();
this.ItemsSource = Children;
this.SetBinding(CarouselView.ItemsSourceProperty, "Children");
BindingContext = this;
}
}
public class CarouselTemplateSelector : DataTemplateSelector
{
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
DataTemplate dt = new DataTemplate();
View civ = (View)item;
return new DataTemplate(() =>
{
return civ;
});
}
}
so you can call it passing Views:
public App()
{
// The root page of your application
MainPage = new ContentPage {
Content = new CarouselViewMultiPage
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Label() { Text="Page 1"},
new Label() { Text="Page 2"},
new Label() { Text="Page 3"},
}
}
};
}
CarouselView has been introduced in Xamarin forms v4.4. You can have a look at this. In additional to CarouselView, IndicatorView is also added to indicate the nth item in the carousel.

windows phone 8 longlistselector show and hide button based on recordid

I have a books list displayed in my long list selector like this
<DataTemplate x:Key="BooksItemTemplate">
<StackPanel Grid.Column="1" Grid.Row="0" VerticalAlignment="Top">
<TextBlock Name="booktitle" Text="{Binding BookTitle,Mode=OneWay}" Style="{StaticResource PhoneTextNormalStyle}" TextWrapping="Wrap" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
<TextBlock Text="{Binding AuthorName,Mode=OneWay}" Style="{StaticResource PhoneTextNormalStyle}" TextWrapping="Wrap" FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
<Button Content="Add To Favourites" Tag="{Binding BookId,Mode=OneWay}" Click="Button_Click_1" ></Button>
</StackPanel>
</Grid>
</DataTemplate>
<phone:LongListSelector x:Name="bookslist" Grid.Row="1"
ListFooter="{Binding}"
ItemsSource="{Binding BooksList}"
Background="Transparent"
IsGroupingEnabled="False"
ListFooterTemplate ="{StaticResource booksListFooter}"
ItemTemplate="{StaticResource BooksItemTemplate}"/>
so there is an add to favourites button beside every book in the list . pressing that button i am entering the pressed book's id in my isolatedstoragesetting like this
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Button bt = (Button)sender;
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
List<long> ListFavourites;
if (settings.Contains("ListFavourites"))
{
ListFavourites = settings["ListFavourites"] as List<long>;
}
else
{
ListFavourites = new List<long>();
}
if(!ListFavourites.Contains(Convert.ToInt64(bt.Tag)))
{
ListFavourites.Add(Convert.ToInt64(bt.Tag));
}
settings["ListFavourites"] = ListFavourites;
settings.Save();
}
problem:
now when loading the above book list(longlistselector) when the page loads i want to show or hide the add to favorites button based on whether the bookid is present in the isolatedstoragesetting or not. what i have tried here is that i have tried to bind the converter to the add to favourite button and also bind the convertparameter with bookid. but the convertparameter doesn't support binding.
so what is the technique i can use to show or hide the add to favourite button based on the book id presence in the favourite list in the isolatedstoragesetting?
how can i hide the button based when clicking it based on the bookid?
You are almost there in thinking to use a converter. The actual idea, when materialized, should look something like this.
First, you will need to implement a converter, in this case, you will need to convert the bookid to a Visibility value.
public class BookIdToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
//value is booking id here, which means that you just need to check against the isolatedStorageSettings
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
In your DataTemplate, the binding should take place like this:
<Button Content="Add To Favourites" Tag="{Binding BookId,Mode=OneWay}"
Click="Button_Click_1" Visibility={Binding BookId,Converter={StaticResource TheConverterCreatedAbove}} >
</Button>
That should do the trick.
The MVVM way would be to expand your ViewModel. It would be much better to add an AddToFavoritesCommand to BookViewModel instead of putting the logic in code behind. If the button is bound to that Command it would automatically go disabled when the Command would properly (with CanExecuteChanged) switch CanExecute to false.
In your case, you can add a property IsFavourite or CanAddToFavoirtes and then use a standard BoolToVisibility converter (the Command execution would set this property and the BookViewModel would be initialized with the correct value read from IsolatedStorage).
All logic behind the presentation of Book and functionalities related to Book belong to BookViewModel.

No DataBinding when rendering a UserControl+ItemsControl in WriteableBitmap?

I want to use a WriteableBitmap to render a programmatically instantiated UserControl to a jpg/png image to use it as a live tile background image in a Windows Phone 7.1 project, but DataBinding is not working as expected when rendering the control.
In general, the UserControl is something like this:
<UserControl>
<Grid x:Name="LayoutRoot" Height="173" Width="173" >
<Grid.Background >
<SolidColorBrush Color="{StaticResource PhoneAccentColor}" />
</Grid.Background >
<Grid.RowDefinitions>
<RowDefinition Height="27"/>
<RowDefinition Height="146"/>
</Grid.RowDefinitions >
<ItemsControl Grid.Row="1" Margin="10,0,0,0" ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyBindingProperty, FallbackValue=xxx}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Text="Hello World" FontSize="22" Margin="5,0,0,0"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Count, FallbackValue=-1}" FontSize="18.667" Margin="123,0,0,0"/>
</Grid>
</UserControl>
When I now put this control onto a PhoneApplicationPage and assign a list with items of my data structure to the DataContext property of the UserControl, everything works fine and I see one TextBlock for each list item and the Text property of that TextBlock is correctly displaying the value of the property of my data structure. Also the last TextBlock on the Grid displays correctly the current count of list items.
BUT when I'm now trying to programmatically create that UserControl, assign the same list to the DataContext and then use a WriteableBitmap to render it to an image file, it seems that all DataBindings within the DataTemplate of the ItemsControl aren't working anymore, they're displaying the FallbackValue now. Although the DataBinding of the outer TextBlock in the Grid is still working perfectly and also I got the correct number of TextBlocks in the StackPanel (= items in the bound list).
Here is my code for creating the the WriteableBitmap:
var tile = new MyTileControl { DataContext = this._myList };
tile.Arrange(new Rect(0, 0, 173, 173));
tile.Measure(new Size(173, 173));
var bmp = new WriteableBitmap(173, 173);
bmp.Render(tile, null);
bmp.Invalidate();
What's the problem with the DataBindings in the DataTemplate when rendering through a WriteableBitmap and how can I solve it?
I think, that your control not fully created yet, and you can't grab bitmap just after creation. Try to use Dispatcher.BeginInvoke or something else for delayed grabbing of image.
Also, add this control to your page and look where is a problem - in control creation or in bitmap? This give you more information about a problem.

WP7 binding UserControl using MVVM [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Binding between Usercontrol with listbox and parent control (MVVM)
I’m trying to bind a UserControl to property on my main page’s viewmodel
The code looks like this:
UserControl xaml:
<UserControl x:Class="myUserControl" ....>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}" >
<ListBox Name="myListBox" ItemsSource="{Binding Path=myItemsSource}"/>
</Grid>
</UserControl>
the codebehind looks like this:
public partial class myUserControl : UserControl
{
public static DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("myItemsSource",
typeof(IEnumerable), typeof(myUserControl), null);
public IEnumerable myItemsSource
{
get
{
return (IEnumerable)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}
}
The UC is used like this in the main page:
<phone:PhoneApplicationPage DataContext="{Binding myViewModel, Source={StaticResource Locator}}" ....>
<Grid x:Name="ContentPanel">
<uc:myUserControl x:Name="ucList" myItemsSource="{Binding Path=DataList}"/>
</Grid>
</phone:PhoneApplicationPage>
and the viewModel for the main page look like this:
public class myViewModel : ViewModelBase
{
public ObservableCollection<myObject> DataList
{
get
{
return _datalist;
}
set
{
if (_dataList != value)
{
_dataList = value;
RaisePropertyChanged("DataList");
}
}
}
}
But when the DataList property is set, the uc List in not populated.
What i'm I missing ?
It's still early and I haven't had my coffee yet, but it looks to me like you might need a data template for your list items. You've defined the ItemsSource but not told the control how to render the items themselves.
What does your list contain? Try binding a data template to one of the list item properites, like this:
<UserControl x:Class="myUsercontrol" ....>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}" >
<ListBox Name="myListBox" ItemsSource="{Binding Path=myItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding SomeListItemProperty}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
EDIT: Are you by chance using MVVM Light? I saw that you mentioned {StaticResource = Locator} in one of the comments. That would be helpful to know.
One other thing you might try is checking if your UserControl is in its own namespace. If you put it in a UserControl folder, it might be. I've had some issues with binding a UserControl when it wasn't in the same namespace as the ViewModel.

WP7: Binding to an element outside pivot.itemtemplate

I've been struggling for a while on this. I'm a bit of a newbie, but i lurked a lot and still couldn't find a solution to my problem, so I decided to post my question here.
I'm binding a pivot to a collection of objects I want to display to create a gallery. Here is my pivot control bound to a list called gallery, where each object contains 2 strings (url and description).
<controls:Pivot ItemsSource="{Binding gallery}" Grid.Row="0" x:Name="galleryPivot">
<controls:Pivot.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Image Source="{Binding url}" />
<Grid Visibility="{Binding ElementName=galleryPivot, Path=DataContext.ShowDetail}">
<ListBox>
<ListBoxItem>
<StackPanel>
<TextBlock Text="{Binding description}" />
</StackPanel>
</ListBoxItem>
</ListBox>
</Grid>
</Grid>
</StackPanel>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
The datacontext is the viewmodel and initialized in the constructor of the page.
Here is my ViewModel:
public class GalleryViewModel : INotifyPropertyChanged
{
public List<Gallery> gallery
{
get { return Globals.pictures; }
}
private Visibility _showDetail = Visibility.Collapsed;
public Visibility ShowDetail
{
get { return _showDetail; }
set {
_showDetail = value;
RaisePropertyChanged("ShowDetail");
}
}
public GalleryViewModel()
{ }
public event PropertyChangedEventHandler PropertyChanged = delegate { return; };
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The gallery object is a list in my ViewModel, as the ShowDetail property. As ShowDetail is outside the scope, I tried to set ElementName as explained here.
The pivot binds well to the gallery list, but when I change the value of ShowDetail, the grid won't hide. I also tried to set ElementName to LayoutRoot but it still won't work.
My question, how can I bind the visibility when it is outside the scope of the itemtemplate?
Within a DataTemplate the ElementName binding refers only to the names of elements that are within that DataTemplate. The data context within your data template is the Gallery instance, not the GalleryViewModel. You could move the ShowDetail property down to the Gallery class instead.
If you'd rather not do that, then an alternative would be to use a proxy for the data context, which you add as a resource to the page and bind to the page's data context (a GalleryViewModel instance presumably). You can then reference that resource as you would any other resource to get at the parent data context.
If you're not familiar with this proxy concept, then Dan Wahlin's post on the subject should help.

Resources