学海无涯

导航

Windows and Dialogs 窗体 对话框

 

 

 

<Window x:Class="WpfTestBlankApp.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTestBlankApp.Models"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="600" Width="500" 
         xmlns:compModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
 xmlns:data="clr-namespace:System.Windows.Data;assembly=PresentationFramework">
    <StackPanel>
        <Button x:Name="openFileDialog" Click="openFileDialog_Click" Content="打开文件"></Button>
        <Button x:Name="openDialog" Click="openDialog_Click" Content="打开模式对话框"></Button>
        <Button x:Name="openModelessDialog" Click="openModelessDialog_Click" Content="打开对话框"></Button>
    </StackPanel>
</Window>
using Microsoft.Win32;
using Prism.Regions;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfTestBlankApp.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string currentPlayer;
        Button[] cells;
        int moveNumber;
        string reporter;
        public MainWindow(IRegionManager regionManager)
        {
            InitializeComponent();
            reportColor = Colors.Red;
            reportFolder = @"E:\电子书\WPF";
        }
        string filename;
        private void openFileDialog_Click(object sender, RoutedEventArgs e)
        {//文件对话框
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.FileName = filename;
            if (dlg.ShowDialog() == true)
            {
                filename = dlg.FileName;
            }
        }
        Color reportColor;
        string reportFolder;
        private void openDialog_Click(object sender, RoutedEventArgs e)
        {//打开模式对话框
         //1. 使用初始值创建并初始化对话框
            SettingsDialog dialog = new SettingsDialog();
            dialog.Owner = this;
            dialog.ReportColor = reportColor;
            dialog.ReportFolder = reportFolder;
            //2.显示对话框,让用户选择新的、经过验证的值
            if (dialog.ShowDialog() == true)
            { //3.使用用户设置的新值
                reportColor = dialog.ReportColor;
                reportFolder = dialog.ReportFolder;
            }
        }

        private void openModelessDialog_Click(object sender, RoutedEventArgs e)
        {//打开无模式对话框
            // Initialize the dialog
            SettingsDialog dlg = new SettingsDialog();
            dlg.Owner = this;
            dlg.ReportColor = reportColor;
            dlg.ReportFolder = reportFolder;
            dlg.Reporter = reporter;
            // Listen for the Apply button and show the dialog modelessly
            dlg.Apply += dlg_Apply;
            dlg.Show();
        }

        void dlg_Apply(object sender, EventArgs e)
        {
            // Pull the dialog out of the event args and apply the new settings
            SettingsDialog dlg = (SettingsDialog)sender;
            reportColor = dlg.ReportColor;
            reportFolder = dlg.ReportFolder;
            reporter = dlg.Reporter;
            // Do something with the dialog properties
        }
    }
}
<Window x:Class="WpfTestBlankApp.Views.SettingsDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTestBlankApp.Views"
        xmlns:model="clr-namespace:WpfTestBlankApp.Models"
        mc:Ignorable="d"
        Title="SettingsDialog" Height="450" Width="800"
        ResizeMode="CanResizeWithGrip" WindowStartupLocation="CenterOwner"
        FocusManager.FocusedElement="{Binding ElementName=reportFolderTextBox}"
        ShowInTaskbar="False">
    <Window.Resources>
        <Style TargetType="Label">
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="Button">
            <Setter Property="Margin" Value="10"/>
            <Setter Property="Padding" Value="5,2"/>
        </Style>

    </Window.Resources>
    <Grid>
        <Grid.Resources>
            <SolidColorBrush x:Key="reportBrush" Color="{Binding ReportColor}" />
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition MinWidth="200" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <!-- 1st row: report folder setting -->
        <Label Grid.Row="0" Grid.Column="0"
 Target="{Binding ElementName=reportFolderTextBox}">Report _Folder</Label>
        <TextBox Grid.Row="0" Grid.Column="1" Name="reportFolderTextBox"
                 ToolTip="{Binding RelativeSource={RelativeSource Self},
            Path=(Validation.Errors)[0].ErrorContent }">
            <TextBox.Text>
                <Binding Path="ReportFolder">
                    <Binding.ValidationRules>
                        <model:FolderMustExist/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <Button Grid.Row="0" Grid.Column="2" Name="folderBrowseButton">...</Button>
        <!-- 2nd row: report color setting -->
        <Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left"
 Name="reportColorButton">
            <StackPanel Orientation="Horizontal">
                <Rectangle Width="15" Height="15" SnapsToDevicePixels="True"
 Fill="{StaticResource reportBrush}" />
                <AccessText Text="Report _Color..." Margin="10,0,0,0" />
            </StackPanel>
        </Button>
        <!-- 3rd row: buttons -->
        <Label Grid.Row="2" Target="{Binding ElementName=reporterTextBox}">_Reporter</Label>
        <TextBox  Grid.Row="2" Grid.Column="1" x:Name="reporterTextBox" 
                 ToolTip="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}">
            <TextBox.Text>
                <Binding Path="Reporter" >
                    <Binding.ValidationRules >
                        <model:NonZeroLength ValidatesOnTargetUpdated="True"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

        <StackPanel Grid.Row="4" Grid.ColumnSpan="3" Orientation="Horizontal"
 HorizontalAlignment="Right" VerticalAlignment="Bottom">
            <Button Name="applyButton" Width="72" Click="applyButton_Click">Apply</Button>
            <Button Name="okButton" IsDefault="True" Width="72" Click="okButton_Click">OK</Button>
            <Button Name="cancelButton" IsCancel="True"  Width="72" >Cancel</Button>
        </StackPanel>
    </Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using WpfTestBlankApp.Models;

namespace WpfTestBlankApp.Views
{
    /// <summary>
    /// SettingsDialog.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsDialog : Window
    {
        public SettingsDialog()
        {
            InitializeComponent();
            //reportFolderTextBox.Text = ReportFolder;
            DataContext = data;
        }
        DialogData data = new DialogData();
        public event EventHandler Apply;
        public Color ReportColor
        {
            get { return data.ReportColor; }
            set { data.ReportColor = value; }
        }
        public string ReportFolder
        {
            get { return data.ReportFolder; }
            set { data.ReportFolder = value; }
        }
        public string Reporter
        {
            get { return data.Reporter; }
            set { data.Reporter = value; }
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            // Validate all controls
            if (ValidateBindings(this))
            {
                DialogResult = true;
            }
        }
        public static bool ValidateBindings(DependencyObject parent)
        {
            // Validate all the bindings on the parent
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule rule in binding.ValidationRules)
                    {
                        ValidationResult result =
                        rule.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expression =
                            BindingOperations.GetBindingExpression(parent, entry.Property);
                            Validation.MarkInvalid(expression,
                            new ValidationError(rule, expression, result.ErrorContent, null));
                            valid = false;
                        }
                    }
                }
            }
            // Validate all the bindings on the children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!ValidateBindings(child)) { valid = false; }
            }
            return valid;
        }

        private void applyButton_Click(object sender, RoutedEventArgs e)
        {//非模式窗口
            if (Apply != null)
            {
                Apply(this, EventArgs.Empty);
            }
        }
    }
}
using System.ComponentModel;
using System.Windows.Media;

namespace WpfTestBlankApp.Models
{
    public class DialogData : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        void Notify(string prop)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
            }
        }
        Color reportColor;
        public Color ReportColor
        {
            get { return reportColor; }
            set { reportColor = value; Notify("ReportColor"); }
        }
        string reportFolder;
        public string ReportFolder
        {
            get { return reportFolder; }
            set { reportFolder = value; Notify("ReportFolder"); }
        }
        string reporter;
        public string Reporter
        {
            get { return reporter; }
            set { reporter = value; Notify(nameof(Reporter)); }
        }

    }
}

 

posted on 2023-01-20 11:50  宁静致远.  阅读(31)  评论(0编辑  收藏  举报