我可以不吃啊 发表于 2024-6-13 20:07:04

DevExpress开辟WPF应用实现对话框总结

说明:


[*]完整代码Github​(https://github.com/VinciYan/DXMessageBoxDemos.git)
[*]DevExpree v23.2.4(链接:https://pan.baidu.com/s/1eGWwCKAr8lJ_PBWZ_R6SkQ?pwd=9jwc 提取码:9jwc)
[*]使用Visual Studio Community 2022
https://img-blog.csdnimg.cn/direct/2f02e85d541b468f84f405792ee6057c.png
简单标准弹窗

使用标准的.NET的MessageBox:
public void BaseMsg()
{
    MessageBox.Show("This is a standard .NET MessageBox", "Title", MessageBoxButton.OK, MessageBoxImage.Information);
}
https://img-blog.csdnimg.cn/direct/a806de0c129e401eb053971e186bf164.png
DevExpress的DXMessageBox

public void DxBaseMsg()
{
    // 显示一个简单的消息框
    DXMessageBox.Show("This is a DevExpress DXMessageBox", "Title", MessageBoxButton.OK, MessageBoxImage.Information);
}
https://img-blog.csdnimg.cn/direct/0db1626d82b04dbb81daf9f054d6aad1.png
DevExpress的IMessageBoxService

在DevExpress WPF中使用IMessageBoxService来显示一个消息框,并根据用户的选择更新按钮的文本,符合MVVM模式的设计原则,保持了视图和视图模型的分离
<Window ...
      xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
      xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
      DataContext="{dxmvvm:ViewModelSource Type=local:ViewModel}">
    <dxmvvm:Interaction.Behaviors>
      <dx:DXMessageBoxService/>
    </dxmvvm:Interaction.Behaviors>

    <dx:SimpleButton Content="{Binding ButtonText}"
                     Command="{Binding SaveConfirmationCommand}"/>
</Window>
public class ViewModel : ViewModelBase {
    public virtual string ButtonText { get; set; } = "Save Changes Button";

    IMessageBoxService MessageBoxService { get { return GetService<IMessageBoxService>(); } }

   
    public void SaveConfirmation() {
      MessageResult result;
      result = MessageBoxService.ShowMessage(
            messageBoxText: "Save Changes?",
            caption: "DXApplication",
            icon: MessageIcon.Question,
            button: MessageButton.YesNoCancel,
            defaultResult: MessageResult.Cancel
      );
      switch (result) {
            case MessageResult.Yes:
                ButtonText = "Changes Saved";
                break;
            case MessageResult.No:
                ButtonText = "Changes Discarded";
                break;
            case MessageResult.Cancel:
                ButtonText = "Continue Editing";
                break;
      }
    }
}
https://img-blog.csdnimg.cn/direct/2a625a36834848bea9a43a9a63787668.png
点击“Yes”按钮,修改按钮显示的文字为“Changes Saved”
https://img-blog.csdnimg.cn/direct/26888cd6ea544f56bc9e49c6ab4d1745.png
DevExpress的DXDialog

DXDialog提供了比标准WPF对话框更强大的功能和更高的机动性。它在定制、样式支持、MVVM集成、功能丰富性和一致的用户体验方面体现出色
DXDialog提供了丰富的功能,比如:


[*]定位:可以轻松控制对话框在屏幕上的位置
[*]巨细:可以设置对话框的宽度和高度
[*]内容:可以将恣意WPF控件添加到对话框中,支持复杂的内容布局
简单控件

public void BaseDXDialog()
{
    var dialog = new DXDialog
    {
      WindowStartupLocation = WindowStartupLocation.CenterScreen,
      Width = 500,
      Height = 300,
      Title = "Custom Dialog",
      Content = new TextBlock { Text = "This is a custom DXDialog", Margin = new Thickness(10) }
    };

    var result = dialog.ShowDialog();
    if (result == true)
    {
      MessageBox.Show("OK clicked");
    }
    else
    {
      MessageBox.Show("Cancel clicked");
    }
}
https://img-blog.csdnimg.cn/direct/f357717de50a49f2afe6f0b858e063cb.png
复杂控件

public void CompDXDialog()
{
    // 创建一个 StackPanel 作为对话框的内容
    var stackPanel = new StackPanel
    {
      Margin = new Thickness(10)
    };

    // 在 StackPanel 中添加控件
    stackPanel.Children.Add(new TextBlock { Text = "Enter your name:", Margin = new Thickness(0, 0, 0, 10) });
    var nameTextBox = new TextBox { Width = 200, Margin = new Thickness(0, 0, 0, 10) };
    stackPanel.Children.Add(nameTextBox);
    stackPanel.Children.Add(new TextBlock { Text = "Select your age:", Margin = new Thickness(0, 0, 0, 10) });
    var ageComboBox = new ComboBox { Width = 200, Margin = new Thickness(0, 0, 0, 10) };
    ageComboBox.ItemsSource = new int[] { 18, 19, 20, 21, 22, 23, 24, 25 };
    stackPanel.Children.Add(ageComboBox);

    // 设置 StackPanel 作为对话框的内容
    var dialog = new DXDialog
    {
      WindowStartupLocation = WindowStartupLocation.CenterScreen,
      Title = "Custom Dialog with Controls",
      Content = stackPanel
};

    // 显示对话框并获取结果
    var result = dialog.ShowDialog();

    // 根据对话框结果进行处理
    if (result == true)
    {
      string name = nameTextBox.Text;
      int? age = ageComboBox.SelectedItem as int?;
      MessageBox.Show($"Name: {name}, Age: {age}");
    }
    else
    {
      MessageBox.Show("Dialog was cancelled.");
    }
}
https://img-blog.csdnimg.cn/direct/33e3fb698279403185280f6a062aef50.png
自定义控件

可以将一个View页面(例如一个用户控件)放置在DXDialog的Content属性中。这样可以使对话框的内容更加复杂和模块化,从而更好地构造和管理代码
以下是一个示例,展示如安在DXDialog中放置一个用户控件:
public void UserControlDXDialog()
{
    // 创建并设置用户控件作为对话框的内容
    var myUserControl = new MyUserControl();         
    var dialog = new DXDialog
    {
      WindowStartupLocation = WindowStartupLocation.CenterScreen,
      Title = "Custom Dialog with UserControl",
      Content = myUserControl
    };         

    // 显示对话框并获取结果
    var result = dialog.ShowDialog();

    // 根据对话框结果进行处理
    if (result == true)
    {
      string name = myUserControl.UserName;
      int? age = myUserControl.UserAge;
      MessageBox.Show($"Name: {name}, Age: {age}");
    }
    else
    {
      MessageBox.Show("Dialog was cancelled.");
    }
}
https://img-blog.csdnimg.cn/direct/2a04fe858c07487e92916a2339eb4c95.png
DevExpress的IDialogService

自定义对话框按钮

SimpleDialogView.xaml
<UserControl x:Class="DXMessageBoxDemos.View.SimpleDialogView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
             xmlns:local="clr-namespace:DXMessageBoxDemos.View"
             xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <dxmvvm:Interaction.Behaviors>
      <dx:CurrentDialogService />
    </dxmvvm:Interaction.Behaviors>

    <StackPanel>
      <ComboBox SelectedItem="{Binding DialogResult}">
            <ComboBox.Items>
                <dxmvvm:MessageResult>Yes</dxmvvm:MessageResult>
                <dxmvvm:MessageResult>No</dxmvvm:MessageResult>
                <dxmvvm:MessageResult>Cancel</dxmvvm:MessageResult>
            </ComboBox.Items>
      </ComboBox>
      <Button Command="{Binding CloseCommand}" Content="Close the dialog from the dialog view model" />
    </StackPanel>
</UserControl>
SimpleDialogViewModel.cs
public class SimpleDialogViewModel : ViewModelBase
{
    public MessageResult DialogResult
    {
      get { return GetProperty(() => DialogResult); }
      set { SetProperty(() => DialogResult, value); }
    }
    protected ICurrentDialogService CurrentDialogService { get { return GetService<ICurrentDialogService>(); } }

   
    public void Close()
    {
      CurrentDialogService.Close(DialogResult);
    }
}
MainViewModel.cs
public MessageResult Result
{
    get { return GetProperty(() => Result); }
    set { SetProperty(() => Result, value); }
}
protected IDialogService DialogService { get { return GetService<IDialogService>(); } }


public void ShowDialog()
{
    Result = DialogService.ShowDialog(dialogButtons: MessageButton.YesNoCancel, title: "Simple Dialog", viewModel: new SimpleDialogViewModel());
}
MainView.xaml
<StackPanel>
    <TextBlock Text="DialogService:"/>
    <Button Command="{Binding ShowDialogCommand}" Content="Show Dialog" />
    <TextBlock Text="{Binding Result, StringFormat='The last result is {0}'}" />
</StackPanel>
https://img-blog.csdnimg.cn/direct/adbfae5fb6d946e7ae07c45aca3f89cb.png
异步按钮

DialogService可以显示异步按钮。这些按钮指示关联的异步操作是否正在举行
public void ShowRegistrationForm()
{
    UICommand registerAsyncCommand = new UICommand(
       id: null,
       caption: "Register Async",
       command: new AsyncCommand<CancelEventArgs>(
         async cancelArgs => {
               try
               {
                   await MyAsyncExecuteMethod();
               }
               catch (Exception e)
               {
                   AsyncMessageBoxService.ShowMessage(e.Message, "Error", MessageButton.OK);
                   cancelArgs.Cancel = true;
               }
         },
         cancelArgs => !string.IsNullOrEmpty(registrationViewModel.UserName)
       ),
       asyncDisplayMode: AsyncDisplayMode.Wait,
       isDefault: false,
       isCancel: false
   );

    UICommand registerCommand = new UICommand(
      id: null,
      caption: "Register",
      command: new DelegateCommand<CancelEventArgs>(
            cancelArgs => {
                try
                {
                  MyExecuteMethod();
                }
                catch (Exception e)
                {
                  AsyncMessageBoxService.ShowMessage(e.Message, "Error", MessageButton.OK);
                  cancelArgs.Cancel = true;
                }
            },
            cancelArgs => !string.IsNullOrEmpty(registrationViewModel.UserName) && !((IAsyncCommand)registerAsyncCommand.Command).IsExecuting
      ),
      isDefault: true,
      isCancel: false
    );

    UICommand cancelCommand = new UICommand(
      id: MessageBoxResult.Cancel,
      caption: "Cancel",
      command: null,
      isDefault: false,
      isCancel: true
    );

    UICommand result = AsyncDialogService.ShowDialog(
      dialogCommands: new List<UICommand>() { registerAsyncCommand, registerCommand, cancelCommand },
      title: "Registration Dialog",
      viewModel: registrationViewModel
    );

    if (result == registerCommand)
    {
      // ...
    }
}

void MyExecuteMethod()
{
    // ...
}

async Task MyAsyncExecuteMethod()
{
    await Task.Delay(2000);
    // ...
}
https://img-blog.csdnimg.cn/direct/8c0616398a8441568d18d804fac5ef76.png
点击“Register Async”,实行异步方法
https://img-blog.csdnimg.cn/direct/f52475c3c5ac4cbfa9b9a7d21b5fb262.png
参考



[*] DialogService | WPF Controls | DevExpress Documentation
[*] Showing Dialogs When Using the MVVM Pattern in WPF or UWP - CodeProject
[*] 如安在 WPF/MVVM 中将参数传递给对话框 | DevExpress 支持 — How to pass param to dialog in WPF/MVVM | DevExpress Support
[*] Implementing Dialog Boxes in MVVM - CodeProject
[*] 对话服务 | WPF 控件 | DevExpress 文档 — DialogService | WPF Controls | DevExpress Documentation
[*] DX消息框服务| WPF 控件 | DevExpress 文档 — DXMessageBoxService | WPF Controls | DevExpress Documentation

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: DevExpress开辟WPF应用实现对话框总结