Having a hard time binding an ObservableCollection
of Tuples to XAML in a Visual Studio 2022 extension.
I'm at least partially trying to follow this tutorial, though it's not quite doing the same thing.
- I set up an
ObservableCollection
property of named tuples. - I initialize that collection with two such tuples.
- I set
DataContext
tothis
of my extension'sUserControl
per tutorial:- "DataContext must be an object, this object is the “ViewModel” of our GUI and all the data bindings will be done on this object. If the data we use are not all combined into one class but exist as our MainWindow’s properties, we set the DataContext to be the MainWindow itself:"
- I set the
ItemsSource
of myItemsControl
in the C#. - I bind to properties of the named Tuple (which seems like fair game) in the XAML.
<Checkbox Foreground="LightGreen" Content="{Binding Name}" IsChecked="{Binding IsChecked}"></CheckBox>
Result:
I get two CheckBox
es with no Content
.
C#
public partial class MyWindowControl : UserControl
{
private ObservableCollection<(string Name, bool IsChecked)> ChutzpahItems { get; set; } =
new ObservableCollection<(string Name, bool IsChecked)>()
{
("Thy Smy Name", true),
("Thy Smy OtherName", true),
};
/// <summary>
/// Initializes a new instance of the <see cref="MyWindowControl"/> class.
/// </summary>
public MyWindowControl()
{
DataContext = this;
this.InitializeComponent();
this.itcChutzpah.ItemsSource = ChutzpahItems;
CheckForPrereqs();
}
// ...
XAML
<UserControl x:Class="MyWindowExtension.MyWindowControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Name="MyToolWindow">
<Grid>
<DockPanel>
<StackPanel
DockPanel.Dock="Top"
Orientation="Vertical"
>
<!-- some other widget stuff removed. -->
<ItemsControl Name="itcChutzpah">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox
Foreground="LightGreen"
Content="{Binding Name}"
IsChecked="{Binding IsChecked}"
></CheckBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<!-- some other widget stuff removed. -->
</DockPanel>
</Grid>
</UserControl>
I mean pretty clearly I AM getting a bound collection, but my bindings have the wrong path or something.
Two questions:
- What am I doing wrong?
- How should I have debugged this?
Tuple<,>
is not the same asValueTuple<,>
. The first one is a class with properties (so it's ok to use with binding), the second one is a struct with fields. – Gastrotrich