I had a query with regards to Win UI and I was hoping someone could help me out with this. I am relatively new to the framework and I was looking at list views and reused some code that was provided on the Microsoft Documentation. Find attached a modified version of the code in question.
<ListView
x:Name="List"
ItemsSource="{x:Bind ViewModel.List}"
Width="400"
SelectionChanged="ListView_SelectionChanged">
<ListView.HeaderTemplate>
<DataTemplate>
<Grid
Background="{ThemeResource SystemBaseHighColor}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="300" />
</Grid.ColumnDefinitions>
<TextBlock Text="Column 1" />
<TextBlock
Grid.Column="1"
Text="Column 2" />
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate
x:Name="TableDataTemplate"
x:DataType="viewmodels:SampleObject">
<Grid
Height="50"
AutomationProperties.Name="{x:Bind ObjectName}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="300" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
VerticalAlignment="Center"
Text="{x:Bind ObjectName}" />
<Image
Grid.Column="1"
Source="{x:Bind ObjectPath}"
HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In this piece of code, I have binded the source of the image to the path I would like it to display. However, if I change the path for the respective object during runtime, it does update the data that is stored in the view model. However, it does not update the image binding. Is there something that I am doing wrong, and how can I make it such that the image automatically updates depending on the value of the path. Is there some method that should be called to update or refresh the list view? Or am I supposed to write the binding code differently?
Many thanks for your time, in advance!
I tried looking at the documentation and reading through most of the properties they have highlighted, but there did not seem to be anything relevant to what I was looking for. I also looked at several threads that could be related to this, but couldn't find anything too relevant, although it is possible I may have overlooked it.
You need to implement INotifyPropertyChanged
to your ViewModel.
With the CommunityToolkit.Mvvm NuGet package, your ViewModel could be something like this.
public partial class SampleObject : ObservableObject
{
// CommunityToolkit.Mvvm's source generator will create
// an UI interactive "ObjectName" property for you.
[ObservableProperty]
private string objectName = string.Empty;
// An "ObjectPath" property will be created.
[ObservableProperty]
private string objectPath = string.Empty;
}
public partial class ViewModel : ObservableObject
{
// A "List" property will be created.
[ObservableProperty]
private ObservableCollection<SampleObject> list = new();
}
You also need to set the Mode
to OneWay
when you use x:Bind
.