There is some strange behavior with XAML x:Bind and attempting to bind to a nullable int:
Binding defintions:
public ObservableCollection<ListObject> List { get; set; }
public class ListObject
{
public int? ID { get; set; }
public string Name { get; set; }
}
XAML
<ListView ItemsSource="{x:Bind ViewModel.List}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValue="{x:Bind ViewModel.SelectedID, Mode=TwoWay}"/>
The following works without issue:
private int _selectedID;
public int SelectedID
{
get { return _selectedID; }
set { _selectedID = value; }
}
This does not work and is giving me an invalid object to int? casting exception:
private int? _selectedID;
public int? SelectedID
{
get { return _selectedID; }
set { _selectedID = value; }
}
Why does the XAML binding work on a regular int whereas the nullable int causes issues?
UPDATED
After looking into this issue a bit more it appears the g.cs file is correctly casting the int, however the cast is not generated automatically if the binding target is a nullable struct.
g.cs file for the int binding target:
private void UpdateTwoWay_25_SelectedItem()
{
if (this.initialized)
{
if (this.dataRoot != null)
{
if (this.dataRoot.ViewModel != null)
{
this.dataRoot.ViewModel.SelectedID = (global::System.Int32)this.obj25.SelectedItem;
}
}
}
}
This is what the g.cs file looks like on the nullable struct:
private void UpdateTwoWay_25_SelectedItem()
{
if (this.initialized)
{
if (this.dataRoot != null)
{
if (this.dataRoot.ViewModel != null)
{
// This line is the issue
this.dataRoot.ViewModel.SelectedID = this.obj25.SelectedItem;
}
}
}
}
Manually updating the g.cs file has the binding working correctly. I don't know if this is an issue with the new x:bind, with WinUI 3 or the Windows App SDK.
Either way, I created a bug in the Microsoft-UI-XAML git: Issue 6558
CodePudding user response:
x:Bind doesn't currently handle null values correctly. As stated in this GitHub issue from 2020, they "will look at fixing this post WinUI 3.0".
