我想實作一個簡單ContentDialog的,它有一個TextBox用戶名。如何將該值傳遞給 UWP 中的頁面?
uj5u.com熱心網友回復:
如何在 UWP 應用程式 C# 中將值從 ContentDialog 傳遞到 Page?
正如 Hans Ke?ing 所說,您可以設定對話框的屬性并在頁面中使用對話框實體加載它。我將提供一種系結方式將值從 ContentDialog 傳遞到 Page。
public sealed partial class LoginDialog : ContentDialog ,INotifyPropertyChanged
{
public LoginDialog()
{
this.InitializeComponent();
}
private string _username;
private string _password;
public string UserNameValue { get { return _username; } set { _username = value; OnPropertyChanged(); } }
public string PasswordValue { get { return _password; } set { _password = value; OnPropertyChanged(); } }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
}
Xaml 代碼
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox
x:Name="UserName"
Grid.Row="0"
Margin="0,0,0,12"
Text="{x:Bind UserNameValue, Mode=TwoWay}" />
<TextBox
x:Name="Password"
Grid.Row="1"
Text="{x:Bind PasswordValue, Mode=TwoWay}" />
</Grid>
用法
var dialog = new LoginDialog();
var res = await dialog.ShowAsync();
if (res == ContentDialogResult.Primary)
{
var password = dialog.PasswordValue;
var userName = dialog.UserNameValue;
}
uj5u.com熱心網友回復:
就您的代碼而言,ContentDialog 只是一個類。一個類可以有屬性。
因此,您可以在顯示對話框之前設定這些屬性。并在對話框關閉后閱讀它們。
因此,您需要向從該文本框填充的 ContentDialog 添加一個屬性 - 如果您正確設定資料系結,您可以“自動”執行此操作。
編輯
所以而不是像
if (await new MyDialog().ShowAsync() == DialogResult.Primary) ...
做類似的事情
// first create an instance (this doesn't show anything yet)
var myDialog = new MyDialog();
// optionally set some properties
myDialog.Username = "some default value";
// now show that dialog
var res = await myDialog.ShowAsync();
// and when it is closed again ...
if (res == DialogResult.Primary)
{
// read the properties of your dialog instance
var theUsername = myDialog.Username;
// and do something with 'theUsername' ...
}
并在該對話框的 XAML 中,將該 Username 屬性系結到文本框的文本(這是確保屬性值更新為文本框最新狀態的最簡單方法)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461932.html
