winui 3 FindAncestor

Simon Ong 21 Reputation points
2023-12-03T15:07:45.8366667+00:00

Hello:

 In Wpf ,  The below code in a page/usercontrol will get the property value from MainWindow Datacontext. 
                    <TextBlock  Text="{Binding DataContext.Arr[2],RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>


What is the equivalent in Winui?

Assuming the MainViewModel is set at MainWindow.xaml.cs as

public MainViewModel mvm { get; } = new();

Regards

Simon

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
750 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 9,431 Reputation points Microsoft Vendor
    2023-12-04T01:37:23.7+00:00

    Hello,

    Welcome to Microsoft Q&A!

    As far as I'm concerned, the RelativeSource property in WinUI3 is not support the FindAncestor mode.

    If you want to bind to a property of a parent element in the visual tree, you could try to set the ElementName property of the binding to the name of the ancestor element to bind to instead of using a RelativeSource.

    And you could try to create a Custom attached properties that sets the DataContext of the target element to a parent element of a specific type.

    Thank you.

    Jeanine


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.