<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock>Hello, world. My name is:</TextBlock>
<TextBlock Name="lblName" Margin="0,10" TextAlignment="Center" FontWeight="Bold">[No
name entered]</TextBlock>
<Button Name="btnEnterName" Click="btnEnterName_Click">Enter name...</Button>
</StackPanel>
private void btnEnterName_Click(object sender, RoutedEventArgs e)
{
Dialogs inputDialog = new Dialogs("Please enter your name:", "Elliott Chen");
if(inputDialog.ShowDialog() == true)
lblName.Text = inputDialog.Answer;
}
新增Dialogs.xaml,
拿掉Hight和Width屬性,改為SizeToContent="WidthAndHeight",讓視窗的大小自動調整,
WindowStartupLocation="CenterScreen"(或CenterOwner),屬性設定視窗被打開時的起始位置,
另外在Cancel button加上IsCancel="True",確保使用者按下此button或Esc會關閉視窗,
IsDefault="True",會把focus指給此button,並按下Enter可以執行此button
<Window x:Class="WpfApplication1.Dialogs"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Input" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen"
ContentRendered="Window_ContentRendered"> // 這裡取消了Hight和Width,新增了其他的屬性
<Grid Margin="15">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Name="lblQuestion" Grid.Column="1">Question:</Label>
<TextBox Name="txtAnswer" Grid.Column="1" Grid.Row="1" MinWidth="250">Answer</TextBox>
<WrapPanel Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Margin="0,15,0,0">
<Button IsDefault="True" Name="btnDialogOk" Click="btnDialogOk_Click" MinWidth="60"
Margin="0,0,10,0">_Ok</Button>
<Button IsCancel="True" MinWidth="60">_Cancel</Button>
</WrapPanel>
</Grid>
</Window>
backend
在constructor多加兩個參數,可以傳入問題和回答,
btnDialogOk_Click method只是傳回一個result,告知WPF,
需要注意的是Window_ContentRendered事件,自動選取txtAnswer的內容,並focuse,
最後的Answer method將txtAnswer裡內容傳回去
// 與一般的作法幾乎一模一樣
public partial class Dialogs : Window
{
public Dialogs(string question, string defaultAnswer = "")
{
InitializeComponent();
lblQuestion.Content = question;
txtAnswer.Text = defaultAnswer;
}
private void btnDialogOk_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void Window_ContentRendered(object sender, EventArgs e)
{
txtAnswer.SelectAll();
txtAnswer.Focus();
}
public string Answer
{
get { return txtAnswer.Text; }
}
}