UWP ListView DataTemplate Bind to Item instead of Property - xaml

How do you bind an item in a data template to the item itself, instead of a property of that item?
I have a user control that takes an item as a model. Given these models:
public class Car
{
public string Name { get; set; }
public Color color { get; set; }
public string Model { get; set; }
}
public MyUserControl : UserControl
{
public Car Model { get; set; }
}
public MyPage : Page
{
public ObservableCollection<Car> CareList { get; set; }
}
I want to do something like this in XAML:
<ListView ItemsSource="{x:Bind CarList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name}">
<!-- But what if I want to bind to the car itself ??? -->
<userControls:MyUserControl Model="{x:Bind Car}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

The comment from #user2819245 is correct, if you do not specify the Path of the binding then the DataContext object will be bound directly instead.
In UWP, if your list source can change at runtime or is delay loaded, then you may also need to specify the Mode=OneWay, this is due to {x:Bind} defaulting to a OneTime binding mode.
This example includes how to set the Mode property in both use cases
<ListView ItemsSource="{x:Bind CarList, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name, Mode=OneWay}">
<!-- Binding to the car itself (as the DataContext of this template) -->
<userControls:MyUserControl Model="{x:Bind Mode=OneWay}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Related

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

Binding IsVisible to property toggled by Switch

I have a Switch bound to a property of an element in a List. I want to bind IsVisible of a button to the same property, but the button's visibility is not changed when the property is changed by the Switch. What am I missing?
XAML:
<StackLayout>
<ListView HorizontalOptions="FillAndExpand" ItemsSource="{Binding EquipmentList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Switch IsToggled="{Binding State}" />
<Button
Command="{Binding BindingContext.DoCommand, Source={x:Reference TestPage}}"
CommandParameter="{Binding .}"
IsVisible="{Binding State}"
Text="Click" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
ViewModel:
private Command<Equipment> _doCommand;
public Command<Equipment> DoCommand => _doCommand ??
(_doCommand = new Command<Equipment>((Equipment obj) => HandleEquipment(obj)));
// Outputs correct Name and State of the list item
private void HandleEquipment(Equipment obj)
{
System.Diagnostics.Debug.WriteLine(obj.Name + ", " + obj.State);
}
Model:
class Equipment
{
public int Id { get; set; }
public string Name { get; set; }
public bool State { get; set; }
public Equipment(int Id, string Name, bool State)
{
this.Id = Id;
this.Name = Name;
this.State = State;
}
}
As Gerald wrote in his first comment: You have to implement the INotifyPropertyChanged interface on your Equipment model (and not just in the ViewModel).
Without this implementation, the elements in the view have no chance to know, that the state changed (in your case the button).
Implementation:
public class Equipment: INotifyPropertyChanged
{
public bool State
{
get => _state;
set =>
{
_state = value;
OnPropertyChanged();
}
}
private bool _state;
// OTHER PROPERTIES
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The call of the method OnPropertyChanged() is important. The IsVisible property of the button recognizes the change and updates his value.
Instead of binding two things to a property, why not have the single item bound (i.e. the switch) and use XAML to show or hide the button:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
</Window.Resources>
<StackLayout>
<ListView HorizontalOptions="FillAndExpand" ItemsSource="{Binding EquipmentList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Switch Name="toggleSwitch" IsToggled="{Binding State}" />
<Button
Command="{Binding BindingContext.DoCommand, Source={x:Reference TestPage}}"
CommandParameter="{Binding .}"
IsVisible="{Binding ElementName=toggleSwitch, Path=IsToggled, Converter={StaticResource BooleanToVisibilityConverter}"
Text="Click" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
It may not be a Window that your StackLayout is in, but if you place a BooleanToVisibilityConverter in your Resources section you'll then be able to use it in your XAML file.
This will mean that if the property name changes in the future you only have one place you need to update in the user interface and you're also using the power of the XAML language.
Also as correctly pointed out by everyone, you need to implement INotifyPropertyChanged in the model in order for the Switch to be updated too.

Mock data not showing when bound to ICollectionView

If I bound my ListBox to ViewModels ObservableCollection or XAML resourced CollectionViewSource, the mock data shows while in design.
Sometimes CollectionViewSource stops showing this data because of some XAML changes, but after rebuilding the code it fills controls back with fake data again.
Grouping, sorting and filtering in my case are controlled in ViewModel (and retried from database) so I decided to move over to ICollectionView property based in ViewModel. Unfortunately Views are no longer getting mock data at all.
Here is simple example of my approaches:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance local:MainWindowViewModel }"
Title="MainWindow" Height="100" Width="525"
>
<Window.Resources>
<CollectionViewSource x:Key="ItemsCollectionViewSource" Source="{Binding ItemsObservableCollection}"/>
</Window.Resources>
<UniformGrid Columns="6">
<ListBox ItemsSource="{Binding ItemsObservableCollection}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding Source={StaticResource ItemsCollectionViewSource}}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsICollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsCollectionView}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsListCollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsBackCollectionViewSource}" Background="LightYellow" />
</UniformGrid>
</Window>
code behind:
namespace Test
{
public partial class MainWindow
{
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
}
}
}
and ViewModel:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
namespace Test
{
public class MainWindowViewModel
{
public ICollectionView ItemsICollectionView { get; set; }
public CollectionView ItemsCollectionView { get; set; }
public ListCollectionView ItemsListCollectionView { get; set; }
public ObservableCollection<string> ItemsObservableCollection { get; set; }
public CollectionViewSource ItemsBackCollectionViewSource { get; set; }
public MainWindowViewModel()
{
ItemsObservableCollection = new ObservableCollection<string> {"a", "b", "c"};
ItemsICollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection);
ItemsCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as CollectionView;
ItemsListCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as ListCollectionView;
ItemsBackCollectionViewSource = new CollectionViewSource {Source = ItemsObservableCollection};
}
}
}
None of methods I have tried in order to move CollectionViewSource to ViewModel allows me to see mock data:
I did some debug comparison on those controls, but they are set pretty same in a run time. I'm not aware of ability to debug at design time.
Is there something I'm missing, or it has to be that way?
Thanks

Why LonglistSelector not display items though it display GroupHeaderItem?

My LonglistSelector only displays GroupHeaderTemplate Data (ImageSource,Title) but ItemTemplate DataTemplate (SubItemTitle, Location) not displayed. How can i solve it?
public class Data
{
public string Title { get; set; }
public string ImageSource { get; set; }
public List<SubItem> SubItems { get; set; }
public Data()
{
SubItems = new List<SubItem>();
}
}
public class SubItem
{
public string SubItemTitle { get; set; }
public string Location { get; set; }
}
<phone:LongListSelector ItemsSource="{Binding DataCollection}" Grid.Row="0" IsGroupingEnabled="True">
<phone:LongListSelector.GroupHeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="{Binding ImageSource}"/>
<TextBlock Text="{Binding Title}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.GroupHeaderTemplate>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SubItemTitle}" Padding="5" FontSize="40"/>
<TextBlock Text="{Binding Location}" Padding="5" FontSize="40"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
You have to convert whatever the class you are using to group the items from inheriting. Try using the List than the IEnumerator.
This one discusses the same longlistselector issue.
Grouped LongListSelector: headers appear, items don't
Hope it helps!
This MSDN example helped me a lot when I had trouble understanding Grouping with LongListSelector
How to display data in a grouped list in LongListSelector for Windows Phone 8
It needs to be Grouped by a Key Value. Of all the of the examples I know of it's always something like this:
List<AlphaKeyGroup<your_data_type>> my_group_list; // or
ObservableCollection<AlphaKeyGroup<your_data_type>> my_group_list;
Not a List that has a property that is a SubList.
AlphaKeyGroup is just a List<T>/ObservableCollection<T> with an extra property for a Key
Think of it this way, in your code how does the LongListSelector know that your "Title" is the group key rather than the "ImageSource"?
If the code on the MSDN page is too complicated to understand, you can always take the easier route and use LINQ using the GroupBy.
Here a SO example: Group by in LINQ

XAML ListBox displays class name instead of class property

Here I have a Listbox configured where the TextBlox in the DataTemplate is set to bind the "Name" Property. But instead it shows the full class name "DomainClasses.Entities.Program". Why?
<Grid DataContext="{Binding _CurrentProgram }">
.....
.....
<ListBox x:Name="ProgramsListBox" Width="600" Height="400" Margin="50,0,50,0" ItemsSource="{Binding _Programs}" VerticalAlignment="Top">
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
</StackPanel>
<DataTemplate>
</ListBox>
----
----
</Grid>
This is the ViewModel class
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
_currentProgram = new Program();
_Programs = new ObservableCollection<Program>();
}
public async void SaveProgram(bool isEditing)
{
_Programs.Add(_currentProgram);
OnPropertyChanged();
}
private Program _currentProgram;
public Program _CurrentProgram
{
get { return _currentProgram; }
set
{
_currentProgram = value;
OnPropertyChanged();
}
}
private ObservableCollection<Program> _programs;
public ObservableCollection<Program> _Programs
{
get
{
return _programs;
}
set
{
this._programs = value;
OnPropertyChanged();
}
}
// Implement INotifyPropertyChanged Interface
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}
This is what you need:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Button/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Noticed the ListBox.ItemTemplate around the DataTemplate.
What you have:
<ListBox x:Name="ProgramsListBox" Width="600" Height="400" Margin="50,0,50,0" ItemsSource="{Binding _Programs}" VerticalAlignment="Top">
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
</StackPanel>
<DataTemplate>
</ListBox>
Creates a ListBox with a DataTemplate as a child (in the same sense that the items in the ItemsSource are children of the ListBox). If I remember correctly, when you set the ItemsSource of a ListBox, all items set in the other fashion are removed. So what you're ending up with is a ListBox with a bunch of Programs in it, which no ItemsTemplate set, so it simply shows the name of the bound class.
You need to add the data template inside listview.itemtemplate and then do the binding. Right now you are adding the data template as a child of the listview.