winui-3winui

In WinUI 3, when I call ContentDialog, it tells me that the current element is already bound to a XamlRoot, but I only call it in one place


In WinUI 3, when I call ContentDialog, it tells me that the current element is already bound to a XamlRoot, but I only call it in one place.

Specific pictures:

details

Call mode:

                <TextBox x:Name="NumberInput" 
                     Margin="10,-10,10,25"
                     Width="60" 
                     Height="60" 
                     Header=" " 
                     Text="{Binding Limit}"
                     TextChanged="UpdateLimit" />

Function specifics:

        private async void UpdateLimit(object sender, TextChangedEventArgs e)
        {
            if (int.TryParse(NumberInput.Text, out int maxNumber))
            {
                viewModel.Limit = maxNumber;
            }
            else
            {
                ContentDialog Dialog = new ContentDialog
                {
                    Title = "1",
                    Content = "1",
                    CloseButtonText = "1"
                };

                ContentDialogResult result = await Dialog.ShowAsync();
            }
        }

I tried looking up the ContentDialog keyword with ctrl+f to confirm that this is the only place I've written it. And I've learned through new bing's query that this problem doesn't usually occur with only one window, so I don't get it.

I'm new to winui, so sorry if I'm asking a stupid question!


Solution

  • You need to set the XamlRoot.

    If you are calling this in a Page, you use the page's XamlRoot:

    ContentDialog Dialog = new ContentDialog
    {
        XamlRoot = this.XamlRoot,
        Title = "1",
        Content = "1",
        CloseButtonText = "1"
    };
    
    ContentDialogResult result = await Dialog.ShowAsync();
    

    If you are calling this in a Window, you use the root element's XamlRoot:

    <Window ...>
        <Grid x:Name="RootGrid">
            ...
        </Grid>
    </Window>
    
    ContentDialog Dialog = new ContentDialog
    {
        XamlRoot = this.RootGrid.XamlRoot,
        Title = "1",
        Content = "1",
        CloseButtonText = "1"
    };
    
    ContentDialogResult result = await Dialog.ShowAsync();