我更喜欢使用不会锁定应用程序的对话框,并远离更传统的 Win32 对话框。
示例
输入对话框隐藏
在此示例中,我使用了基于 MVVM 的解决方案的简化版本,我正在用于我的应用程序。它可能不漂亮,但应该让您对它背后的基础有一个扎实的了解。
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<Button Content="Cool Button" x:Name="CoolButton" Click="CoolButton_Click"/>
<ListBox x:Name="MyListBox"/>
</StackPanel>
<!-- It's important that this is in the end of the XAML as it needs to be on top of everything else! -->
<Grid x:Name="InputBox" Visibility="Collapsed">
<Grid Background="Black" Opacity="0.5"/>
<Border
MinWidth="250"
Background="Orange"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="0,55,0,55"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<StackPanel>
<TextBlock Margin="5" Text="Input Box:" FontWeight="Bold" FontFamily="Cambria" />
<TextBox MinWidth="150" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="InputTextBox"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="YesButton" Margin="5" Content="Yes" Background="{x:Null}" Click="YesButton_Click"/>
<Button x:Name="NoButton" Margin="5" Content="No" Background="{x:Null}" Click="NoButton_Click" />
</StackPanel>
</StackPanel>
</Border>
</Grid>
</Grid>
</Window>
显示此对话框非常容易,因为您只需将InputBox 网格的可见性设置为可见。然后,您只需处理是/否按钮并从 TextBox 中获取输入文本。
因此,您只需将Visibility 选项设置为Visible,而不是使用需要ShowDialog() 的代码。在这个例子中还有一些事情要做,我们将在代码隐藏中处理,例如在处理是/否按钮点击后清除 InputText 框。
代码隐藏:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CoolButton_Click(object sender, RoutedEventArgs e)
{
// CoolButton Clicked! Let's show our InputBox.
InputBox.Visibility = System.Windows.Visibility.Visible;
}
private void YesButton_Click(object sender, RoutedEventArgs e)
{
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
MyListBox.Items.Add(input); // Add Input to our ListBox.
// Clear InputBox.
InputTextBox.Text = String.Empty;
}
private void NoButton_Click(object sender, RoutedEventArgs e)
{
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Clear InputBox.
InputTextBox.Text = String.Empty;
}
}
}
代码隐藏可以使用依赖关系轻松完成,或者在本例中作为 ViewModel 逻辑,但为简单起见,我将其保留在代码隐藏中。