You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WINUI3中如何获取ContentDialog控件的用户选择返回值?

WINUI3 ContentDialog中获取Page内ComboBox选中项的解决方案

方法一:通过公共属性暴露选中项

1. 修改AddSitePage代码后台

在AddSitePage中添加公共属性,直接返回ComboBox的选中项:

public class AddSitePage : Page
{
    // 替换为你的站点实际类型,比如Site
    public object SelectedSite => cboSites.SelectedItem;

    // 原有的站点集合定义,示例用ObservableCollection
    public ObservableCollection<object> sites { get; set; } = new();

    public AddSitePage()
    {
        InitializeComponent();
        // 这里添加sites集合的初始化逻辑,比如从数据源加载
    }
}

如果调用代码和AddSitePage不在同一个程序集,需要给XAML中的ComboBox添加x:FieldModifier="Public",确保控件可以被外部访问:

<ComboBox Name="cboSites" x:FieldModifier="Public" ItemsSource="{x:Bind sites}" SelectionChanged="cboSites_SelectionChanged"/>

2. 在调用页面获取选中项

保存AddSitePage的实例,在对话框关闭后通过公共属性获取选中内容:

private async void btnAddSite_Click(object sender, RoutedEventArgs e)
{
    var addSitePage = new AddSitePage();
    var dialog = new ContentDialog();

    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 = addSitePage;

    var result = await dialog.ShowAsync();

    if (result == ContentDialogResult.Primary)
    {
        var selectedSite = addSitePage.SelectedSite;
        // 这里添加选中站点的后续处理逻辑
    }
}

方法二:通过ContentDialog按钮事件直接获取

无需修改AddSitePage的属性,直接在主按钮点击事件中访问ComboBox:

private async void btnAddSite_Click(object sender, RoutedEventArgs e)
{
    var addSitePage = new AddSitePage();
    var dialog = new ContentDialog();

    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 = addSitePage;

    // 绑定主按钮点击事件
    dialog.PrimaryButtonClick += (s, args) =>
    {
        var selectedSite = addSitePage.cboSites.SelectedItem;
        // 直接在这里处理选中项,或者保存到变量后续使用
    };

    await dialog.ShowAsync();
}

关键注意点

  • 确保cboSites.SelectedItem的类型与你的站点实体类型匹配,必要时进行显式类型转换。
  • 跨程序集访问时,必须设置ComboBox的x:FieldModifier="Public",否则无法访问该控件。

内容的提问来源于stack exchange,提问作者Jason Coulls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:45:56