How to add multiple pivots using DataTemplate in winrt UWP? - xaml

I have a condition where I want to add multiple PivotItems(which is dynamic).
ie; I have a List<CustomModel> whose size is dynamic, And for every item in the List I want to create a PivotItem with header as CustomModel.Title.
Is it possible to achieve this with xaml alone by creating a DataTemplate and binding it to a Pivot?

It is surely possible. See below sample solution
<Pivot x:Name="TestPivot">
<Pivot.HeaderTemplate>
<DataTemplate x:DataType="local:TestClass">
<TextBlock Text="{Binding HeaderTitle, Mode=OneWay}"/>
</DataTemplate>
</Pivot.HeaderTemplate>
<Pivot.ItemTemplate>
<DataTemplate x:DataType="local:TestClass">
<Grid>
<TextBlock Text="{Binding Content, Mode=OneWay}"/>
</Grid>
</DataTemplate>
</Pivot.ItemTemplate>
</Pivot>
Code behind for simulating the binding
public sealed partial class BlankPage6 : Page
{
ObservableCollection<TestClass> SampleSource = new ObservableCollection<TestClass>();
public BlankPage6()
{
this.InitializeComponent();
SampleSource.Add(new TestClass { HeaderTitle = "Test Header1", Content = "Test content 1" });
SampleSource.Add(new TestClass { HeaderTitle = "Test Header2", Content = "Test content 2" });
SampleSource.Add(new TestClass { HeaderTitle = "Test Header3", Content = "Test content 3" });
TestPivot.ItemsSource = SampleSource;
}
}
public class TestClass
{
public string HeaderTitle { get; set; }
public string Content { get; set; }
}
Output:

Related

TreeViewItem template click/select/highlight issue

I am new to WinUI 3 and I am currently building a TreeView (CommunityToolkit) where I can drag/drop TreeViewItems on top of each other. The TreeViewItem that I have consist of 3 parts, a group name, a display name and children items. The drag/drop part of the code works fine, however there is an issue whereby clicking on an item doesn’t always select/highlight it and I cannot seem to find the root issue as to why. See image below.
In the image above, the first item is "selected" as I would like it to be with the blue highlight to the left. But when I click on either of the other 2 items (Level 1 or Level 2), I have observed the following behaviours.
A click on "U" or "Level 1" does not select the item. There is some "pressed" style showing, but once the mouse button is released nothing happens. There is no highlight or selected style present
A click just above or below the red line selects the item as I expect it to.
See the XAML below
<Grid>
<Border BorderThickness="2" BorderBrush="DimGray">
<TreeView AllowDrop = "True"
CanDragItems="True"
CanReorderItems = "False"
ItemsSource="{x:Bind Items}"
SelectedItem="{x:Bind SelectedDemoItem, Mode=TwoWay}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:DemoItem">
<TreeViewItem AllowDrop="True"
CanDrag="True"
CollapsedGlyph=""
ExpandedGlyph=""
IsExpanded="True"
ItemsSource="{x:Bind Children}"
Padding="-10,0,0,0">
<TreeViewItem.Content>
<StackPanel AllowDrop="True"
BorderBrush="Red"
BorderThickness="1"
CanDrag="True"
Orientation="Horizontal">
<TextBlock FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
Margin="0,0,10,0"
MinWidth="30"
TextAlignment="Center"
Text="{x:Bind Group}" />
<TextBlock Text="{x:Bind DisplayName}" Margin="0,0,5,0"/>
</StackPanel>
</TreeViewItem.Content>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
</Grid>
And the code-behind
public sealed partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
FillData();
}
private void FillData()
{
var level0 = new DemoItem { DisplayName = "Level 0", Group = Groups.M };
var level1 = new DemoItem { DisplayName = "Level 1", Group = Groups.U };
var level2 = new DemoItem { DisplayName = "Level 2", Group = Groups.C };
level1.Children.Add(level2);
level0.Children.Add(level1);
Items.Add(level0);
Items.Add(level0);
}
public ObservableCollection<DemoItem> Items { get; } = new();
public DemoItem SelectedDemoItem { get; set; }
}
public enum Groups
{
S, M, U, C
}
public class DemoItem
{
public string DisplayName { get; set; }
public ObservableCollection<DemoItem> Children { get; } = new();
public Groups Group { get; set; }
}
For the purpose of this test, I have removed all drag/drop code as they have no affect on the problem above. However, it may help to mention that I have seen this problem occur only when CanDrag is set to True within my item template.
Any help to fix this will be greatly appreciated.
Click events won't reach the TreeViewItem because of the TextBlocks. The easiest way is to disable IsHistTestVisible on both TextBlocks.
<TextBlock
MinWidth="30"
Margin="0,0,10,0"
FontSize="14"
FontWeight="ExtraBold"
IsColorFontEnabled="True"
IsHitTestVisible="False"
Text="{x:Bind Group}"
TextAlignment="Center" />
<TextBlock
Margin="0,0,5,0"
IsHitTestVisible="False"
Text="{x:Bind DisplayName}" />

Binding not updating WinUI 3

I'm using WinUI in combination with the microsoft MVVM toolkit.
However im experiencing some issues with Binding and can't figure out where the problem lies.
The ViewModel and models used within the ViewModel are of type observableObject. The Command is fired, and the data is fetched. However the binding is not showing a result in the UI, unless i change the xaml and hot reload the change.
My page:
<Page
x:Class="ThrustmasterGuide.Pages.WheelBasePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ThrustmasterGuide.Pages"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:model="using:ThrustmasterGuide.DataAccess.Context.Model"
xmlns:wheelbase="using:ThrustmasterGuide.ViewModel.Wheelbase"
xmlns:xaml="using:ABI.Microsoft.UI.Xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:converters="using:ThrustmasterGuide.Converters"
xmlns:wheelBase="using:ThrustmasterGuide.Model.WheelBase"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance wheelbase:WheelBaseViewModel, IsDesignTimeCreatable=True}">
<Page.Resources>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
<converters:InvertBoolToVisibilityConverter x:Key="InvertBoolToVisibilityConverter" />
</Page.Resources>
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:EventTriggerBehavior.Actions>
<core:InvokeCommandAction Command="{x:Bind ViewModel.LoadWheelBaseCommand}" />
</core:EventTriggerBehavior.Actions>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
<StackPanel Padding="16 16 16 16" Orientation="Vertical">
<StackPanel>
<TextBlock FontSize="18" Text="{x:Bind ViewModel.WheelBase.Name}" />
<TextBlock FontSize="18" Text="Symptomen:" />
<TextBlock Text="Kies hieronder een symptoom uit om te starten." />
<ProgressRing IsActive="true"
Visibility="{x:Bind ViewModel.LoadWheelBaseCommand.IsRunning, Converter={StaticResource BoolToVisibilityConverter}}" />
<TreeView ItemsSource="{x:Bind ViewModel.WheelBase.Symptoms, Mode=OneWay}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="wheelBase:SymptomModel">
<TreeViewItem ItemsSource="{x:Bind Children}" Content="{x:Bind Description}" />
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</StackPanel>
<Button VerticalAlignment="Bottom" Command="{x:Bind ViewModel.LoadWheelBaseCommand}"
Content="Refresh">
</Button>
</StackPanel>
My ViewModel:
public class WheelBaseViewModel : ObservableRecipient
{
public WheelBaseModel WheelBase { get; set; }
public string WheelBaseName { get; set; }
private readonly WheelBaseService _wheelBaseService;
public IAsyncRelayCommand LoadWheelBaseCommand { get; }
public WheelBaseViewModel(WheelBaseService wheelBaseService)
{
_wheelBaseService = wheelBaseService;
LoadWheelBaseCommand = new AsyncRelayCommand(FetchWheelBase);
}
public async Task FetchWheelBase()
{
WheelBase = await _wheelBaseService.GetWheelBase(WheelBaseName);
}
}
My model:
namespace ThrustmasterGuide.Model.WheelBase
{
public class WheelBaseModel : ObservableObject
{
public string Name { get; set; }
public ObservableCollection<SymptomModel> Symptoms { get; set; }
}
}
My Code behind:
public sealed partial class WheelBasePage : Page
{
public WheelBasePage()
{
this.InitializeComponent();
this.DataContext = App.Current.Services.GetService<WheelBaseViewModel>();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.ViewModel.WheelBaseName = e.Parameter as string;
}
public WheelBaseViewModel ViewModel => (WheelBaseViewModel)DataContext;
}
What is it that i missed to make the UI bind to the WheelBaseModel values?
Update I added mode=OneWay, but still not updating.
Should it be noted that im showing pages within a content frame after navigation?
{x:Bind} has a default mode of OneTime, unlike {Binding}, which has a default mode of OneWay.
I believe you need to use SetProperty so it's known when to raise such events?
https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/observableobject
namespace ThrustmasterGuide.Model.WheelBase
{
public class WheelBaseModel : ObservableObject
{
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
public ObservableCollection<SymptomModel> Symptoms { get; set; }
}
and also bind mode = OneWay
<TextBlock FontSize="18" Text="{x:Bind ViewModel.WheelBase.Name, Mode=OneWay}" />
No indication that your properties notify of their changes.
https://learn.microsoft.com/dotnet/api/system.componentmodel.inotifypropertychanged

CarouselView not rendering on initial page load but renders on XAML Hot Reload

I'm trying to add a CarouselView to display the images the user has picked from their device. Upon debugging, after picking files the CarouselView does not render with the images I've chosen, not even the Frame itself is rendered. After messing around with the XAML, I realized that the CarouselView actually does exist and when I just save the XAML file while debugging, XAML Hot Reload kicks in and the CarouselView renders perfectly.
Here is my XAML code for the CarouselView:
<CarouselView x:Name="preview" IsVisible="True" ItemsSource="{Binding Files}">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
IsVisible="True"
BorderColor="Black"
CornerRadius="5"
Margin="20"
HeightRequest="500"
WidthRequest="500"
HorizontalOptions="Center"
VerticalOptions="Start">
<StackLayout>
<Label TextColor="Black" Text="{Binding FileName}"></Label>
<Image Source="{Binding FullPath}"
Aspect="AspectFill"
HeightRequest="500"
WidthRequest="500"
VerticalOptions="Center"/>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
and here is the code behind:
public FileView( IEnumerable<FileResult> pF)
{
InitializeComponent();
BindingContext = this;
this.pickedFiles = pF;
}
private IEnumerable<FileResult> pickedFiles;
public IEnumerable<FileResult> Files
{
get => pickedFiles;
}
I am utilizing a FileResult object as part of the Xamarin.Essentials plugin to get the files form the device, I've successfully binded the filepath and file name from each file into the CarouselView. The issues i'm facing now is that it's not rendering on the first attempt.
Tested on an Android device if that helps.
According to your description, I suggest you can use ObservableCollection<T> instead of IEnumerable<T>, because ObservableCollection implement INotifyPropertyChanged interface, to notify the view when data changed or update.
the code behind, you can take a look:
public partial class Page2 : ContentPage
{
public ObservableCollection<FileResult> Files { get; set; }
public Page2()
{
InitializeComponent();
Files = new ObservableCollection<FileResult>();
loaddata();
this.BindingContext = this;
}
private void loaddata()
{
Files.Add(new FileResult() { FileName="image 1",FullPath="a5.jpg"});
Files.Add(new FileResult() { FileName = "image 2", FullPath = "a6.jpg" });
Files.Add(new FileResult() { FileName = "image 3", FullPath = "a7.jpg" });
Files.Add(new FileResult() { FileName = "image 4", FullPath = "a8.jpg" });
Files.Add(new FileResult() { FileName = "image 5", FullPath = "a9.jpg" });
}
}
public class FileResult
{
public string FileName { get; set; }
public string FullPath { get; set; }
}

DataBinding inside data template in UWP

I have a usercontrol as follows which has DataTemplate. I want to bind the data inside the DataTemplate to a property inside the DataContext. In Uwp frustratingly they don't have ancestor type, how can I make my thing to work. I have refered this post UWP Databinding: How to set button command to parent DataContext inside DataTemplate but it doesn't work. Please help.
UserControl:
<local:CommonExpanderUserControl>
<local:CommonExpanderUserControl.ExpanderContent>
<DataTemplate x:DataType="Data:VmInstrumentSettingsLocal">
<StackPanel>
<TextBlock Text="{Binding LisLocalSettings.SomeText}"/>
<controls:ButtonBadged x:Name="ButtonApplyLisLocalChanges" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"
x:Uid="/Application.GlobalizationLibrary/Resources/InstrumentSettingsViewButtonApply"
HorizontalAlignment="Center"
Margin="8"
Command="{Binding LisLocalSettings.SaveLisSettings}"/>
</StackPanel>
</DataTemplate>
</local:CommonExpanderUserControl.ExpanderContent>
</CommonExpanderUserControl>
In my UserControl xaml.cs as follows. I want to bind the button command to Command property inside the LisLocalSettings, but it won't work.
public InstrumentSetupLocalSettingsView()
{
this.InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty LisLocalSettingsProperty = DependencyProperty.Register(
nameof(LisLocalSettings),
typeof(VmInstrumentSettingsLisLocal),
typeof(InstrumentSetupLocalSettingsView),
new PropertyMetadata(default(VmInstrumentSettingsLisLocal)));
public VmInstrumentSettingsLisLocal LisLocalSettings
{
get => (VmInstrumentSettingsLisLocal) GetValue(LisLocalSettingsProperty);
set => SetValue(LisLocalSettingsProperty, value);
}
DataBinding inside data template in UWP
You could place Command in data source, but if the data source is collection, we need implement multiple command instance. In general, we place the command in current DataContext that could be reused. For the detail steps please refer the following.
<Page.Resources>
<DataTemplate x:Key="HeaderTemplate">
<StackPanel
x:Name="ExpanderHeaderGrid"
Margin="0"
Padding="0"
HorizontalAlignment="Stretch"
Background="Red"
Orientation="Vertical"
>
<TextBlock x:Name="TextBlockLisSharedSettingsTitle" Text="{Binding}" />
<Button Command="{Binding ElementName=RootGrid, Path=DataContext.BtnCommand}" Content="{Binding}" />
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid x:Name="RootGrid">
<uwpControls:Expander Header="hello" HeaderTemplate="{StaticResource HeaderTemplate}" />
</Grid>
Code Behind
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
}
public ICommand BtnCommand
{
get
{
return new CommadEventHandler<object>((s) => BtnClick(s));
}
}
private void BtnClick(object s)
{
}
}
public class CommadEventHandler<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<T> action;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.action((T)parameter);
}
public CommadEventHandler(Action<T> action)
{
this.action = action;
}
}

Change color in listview item and remove item UWP

I would remove an item with button inside listview item and change color of ellipse with another button in listview item.
The class product code:
class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
The xaml mainpage code:
<Page
x:Class="ListViewTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ListViewTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="Page_Loaded">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="ListViewProducts"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
FontSize="18"
BorderThickness="0"
Width="600"
Height="800"
HorizontalAlignment="Center"
VerticalAlignment="Center"
ItemsSource="{Binding LineItems}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10">
<Grid HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0">
<Ellipse x:Name="EllipseColor" HorizontalAlignment="Left" Height="20" Stroke="Black" VerticalAlignment="Top" Width="20" StrokeThickness="1"/>
</Grid>
<TextBlock Text="{Binding Name}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding Price}" Margin="5,0,0,0"/>
<Button x:Name="btnRemove" Click="btnRemove_Click" Height="20" Width="60" Margin="5"/>
<Button x:Name="btnChangeColor" Click="btnChangeColor_Click" Height="20" Width="60" Margin="5"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
The code behind of mainpage:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
ObservableCollection<Product> _listProduct = new ObservableCollection<Product>();
_listProduct = new ObservableCollection<Product>
{
new Product
{
Name = "Phone",
Price = 100
},
new Product
{
Name = "TV",
Price = 120
},
new Product
{
Name = "Computer",
Price = 80
},
new Product
{
Name = "Laptop",
Price = 250
},
new Product
{
Name = "Tablet",
Price = 150
},
new Product
{
Name = "Monitor",
Price = 200
},
};
ListViewProducts.ItemsSource = _listProduct;
}
private void btnRemove_Click(object sender, RoutedEventArgs e)
{
// Code to remove item
}
private void btnChangeColor_Click(object sender, RoutedEventArgs e)
{
// Code to color EllipseColor
}
}
With btnRemove i would delete listview item and with btnChangeColor i would color red the fill of EllipseColor, in btnChangeColor_Click i would the index of item.
Thanks in advance.
It looks to me like you've got several issues. First off is that you're setting your ListView source via binding to an apparently non-existent collection, as well as setting it in C#. You should move it to using a proper binding. For example, in MainPage.xaml.cs:
private ObservableCollection<Product> _products = new ObservableCollection<Product>();
public ObservableCollection<Product> Products { get => _products; set => _products = value; }
And then bind to it:
<ListView ItemsSource={x:Bind Products, Mode=OneWay} />
Then, in btnRemove_Click, you can just remove the item from the collection:
var product = (sender as Button).DataContext as Product;
Products.Remove(product);
As for coloring the Ellipse, you shouldn't really do that in C#. Instead, you should have a Status property on your Product class, and then change that property.
First off, you'll need to make sure your property changes fire notifications.
public class Product : INotifyPropertyChanged
{
private string _status;
public string Status
{
get => _status;
set
{
_status = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Status)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Then change the property.
var product = (sender as Button).DataContext as Product;
product.Status = "invalid";
Then in your XAML, use a binding converter to change the Ellipse's Fill property based on the status. E.g.
using System;
using Windows.UI;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
public class StatusConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language) =>
new SolidColorBrush(value.ToString() == "invalid" ? Colors.Red : Colors.Gray);
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
throw new NotImplementedException();
}
You'll then need to add the converter to your resources.
<Page...>
<Page.Resources>
<locationofyourconverter:StatusConverter x:Key="StatusConverter" />
</Page.Resources>
...
<Ellipse Fill={Binding Status, Mode=OneWay, Converter={StaticResource StatusConverter}} />