How to bind ListView ItemsSource programmatically in C++/WinRT, WinUI 3

494 Views Asked by At

I'm trying to programmatically set up a binding for a ListView ItemsSource in WinUI 3 and was hoping that something similar to how it's done in Wpf (see this answer) is possible but i cannot find a ItemsSourceProperty in winrt::Microsoft::UI::Xaml::Controls::ListView or winrt::Microsoft::UI::Xaml::Controls::IItemsControl.

I did bind it successfully in Xaml

<ListView ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Values, Mode=OneWay}"

so i was hoping that it's also possible in code.

Am i searching at the wrong place? Is it possible to do this in code?

Example:

if (auto list = GetTemplateChild(L"myList").try_as<winrt::Microsoft::UI::Xaml::Controls::ListView>())
{
    winrt::Microsoft::UI::Xaml::Data::Binding binding;
    binding.Mode(winrt::Microsoft::UI::Xaml::Data::BindingMode::OneWay);
    binding.Path(winrt::Microsoft::UI::Xaml::PropertyPath(L"MySourceProperty"));
    binding.Source(mySourceControl);
    list.SetBinding(winrt::Microsoft::UI::Xaml::Controls::ListView::ItemsSourceProperty(), binding);
}
1

There are 1 best solutions below

0
ridilculous On

Actually it's simple; instead of the convenience from Wpf where the ItemsSource can be taken directly from the Listview, winrt::Microsoft::UI::Xaml::Controls::ItemsControl::ItemsSourceProperty is needed here.

Example:

if (auto list = GetTemplateChild(L"myList").try_as<winrt::Microsoft::UI::Xaml::Controls::ListView>())
{
    winrt::Microsoft::UI::Xaml::Data::Binding binding;
    binding.Mode(winrt::Microsoft::UI::Xaml::Data::BindingMode::OneWay);
    binding.Path(winrt::Microsoft::UI::Xaml::PropertyPath(L"MySourceProperty"));
    binding.Source(mySourceControl);
    list.SetBinding(winrt::Microsoft::UI::Xaml::Controls::ItemsControl::ItemsSourceProperty(), binding);
}