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 development | Windows App SDK
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jeanine Zhang-MSFT 11,356 Reputation points Microsoft External Staff
    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.