I am building a weather related application. It's C# using WINUI3. Everything was going swimmingly, until I hit this issue...
I have a XAML page as follows:
<Page
x:Class="WeatherStudio.Pages.AddSitePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<TextBlock Text="Please choose a site to add:" TextWrapping="Wrap" />
<ComboBox Name="cboSites" ItemsSource="{x:Bind sites}" SelectionChanged="cboSites_SelectionChanged"/>
</StackPanel>
</Page>
The calling page has a button, which when pressed, loads the above XAML into a ContentDialog and shows it to the user. The code-behind on the ContentDialog populates the combobox just fine.
private async void btnAddSite_Click(object sender, RoutedEventArgs e)
{
ContentDialog dialog = new ContentDialog();
// XamlRoot must be set in the case of a ContentDialog running in a Desktop app
dialog.XamlRoot = this.XamlRoot;
dialog.Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style;
dialog.Title = "Choose new site";
dialog.PrimaryButtonText = "Add Site";
dialog.CloseButtonText = "Cancel";
dialog.DefaultButton = ContentDialogButton.Primary;
dialog.Content = new AddSitePage();
ContentDialogResult result = await dialog.ShowAsync();
}
The problem is after the user has hit the primary button, I cannot fathom how to see what they selected. I've tried bindings, public properties, and such and keep running into the same issue - what happens in the ContentDialog is not visible to me afterwards.
Now, I could refactor this into a regular page - but before I do that, is it possible for me to get a result like that from a ContentDialog?
Thanks,
Jason
You can create methods to get values from your AddSitePage
.
AddSitePage.xaml.cs
using Microsoft.UI.Xaml.Controls;
using System.Collections.ObjectModel;
namespace ContentDialogs;
public sealed partial class AddSitePage : Page
{
public AddSitePage()
{
this.InitializeComponent();
}
public ObservableCollection<string> sites = new()
{
"Site A",
"Site B",
"Site C",
};
public string? GetSelectedSite() => this.cboSites.SelectedItem as string;
}
And get the selected item like this:
if (await dialog.ShowAsync() is ContentDialogResult.Primary)
{
this.selectedSite.Text = addSitePage.GetSelectedSite();
}