MessageBox
MessageBoxResult result = MessageBox.Show("確定要退出派工單?", "派工單維護", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.No) return;
當需要顯示自訂的對話方框, 通知使用者一些訊息, 或者需由使用者輸入資料時, 自訂對話方框就能派上用場了, 如下圖
上面其實就是一個新的WPF Window, 在主程式中new 出這個視窗後, 使用ShowDialog() 顯示出來.
製作WPF Window
首先於專案中加入新增項目, 選取WPF(視窗), 並於XAML 寫入如下代碼.
請注意下面的取消按鈕中, 設定IsCancel=true, 表示按下取消後, 對話方框就會自動消失, 不需要再寫close().
<Grid>
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFC2FB97" Offset="0"/>
<GradientStop Color="#FF05896D" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<Label Content="請輸入位址" HorizontalContentAlignment="Center" FontSize="18"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBox x:Name="txt1" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="30" Width="70" BorderBrush="Black" />
<TextBox x:Name="txt2" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="30" Width="70" BorderBrush="Black" Margin="10,0,0,0" />
<TextBox x:Name="txt3" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Height="30" Width="70" BorderBrush="Black" Margin="10,0,0,0" />
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,10,0,0">
<Button x:Name="btnCancel" Content="取消" Width="100" Height="30" IsCancel="True"/>
<Button x:Name="btnOk" Content="確定" Width="100" Height="30" Click="btnClick"/>
</StackPanel>
</StackPanel>
</Grid>
致於C#程式主体中, 則撰寫如下
監色的DialogResult=true/false, 是在主程式中ShowDialog()後的傳回值, 由此判定是按了確定按鈕, 或是按了取消的按鈕
public partial class AddrDialog : Window { public string ip1, ip2, ip3; public AddrDialog() { InitializeComponent(); } private void btnClick(object sender, RoutedEventArgs e) { switch (((Button)sender).Name) { case "btnCancel": DialogResult = false; break; case "btnOk": ip1 = txt1.Text; ip2 = txt2.Text; ip3 = txt3.Text; DialogResult = true; break; } }
主程式控制及取回資料
主程式直接new 出這個新的視窗, 並使用ShowDialog()顯示出來. 若要取得裏面的資料, 則調用物件變數即可.
private void btnFunction_Click(object sender, RoutedEventArgs e) { dialog.AddrDialog d = new dialog.AddrDialog(); if(d.ShowDialog()==true) { MessageBox.Show(d.ip1); } }