WPF中Prism框架的应用

WPF中Prism框架的应用

仓库地址:Link

1 下载Style,Prism包

1.1 TestUIForPrism.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
  <ItemGroup>
    <None Remove="Resources\Eric.ico" />
    <None Remove="Resources\EricssonBuiding.jpg" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="MaterialDesignThemes" Version="4.9.0" />
    <PackageReference Include="Prism.Unity" Version="8.1.97" />
    <PackageReference Include="WindowsAPICodePack-Shell" Version="1.1.1" />
  </ItemGroup>
  <ItemGroup>
    <Resource Include="Resources\Eric.ico" />
  </ItemGroup>
</Project>

1.2 App.xaml

<prism:PrismApplication x:Class="TestUIForPrism.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestUIForPrism"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"   
             xmlns:prism="http://prismlibrary.com/" >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <materialDesign:BundledTheme BaseTheme="Dark" PrimaryColor="LightBlue" SecondaryColor="DeepOrange" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>         
    </Application.Resources>
</prism:PrismApplication>

code behind:

using Prism.Ioc;
using System.Windows;
using TestUIForPrism.Views;

namespace TestUIForPrism
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<Analyzer>();
            containerRegistry.RegisterForNavigation<Maker>();
        }
    }
}

2 Views

2.1 MainWindow.xaml

<Window x:Class="TestUIForPrism.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.FontWeight="Medium"
        TextElement.FontSize="14"
        FontFamily="{materialDesign:MaterialDesignFont}"        
        Icon="../Resources/Eric.ico"
        Title="{Binding Title}" Height="700" Width="700" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="3*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Row="0" Grid.ColumnSpan="3" Margin="30" Orientation="Horizontal">
            <Button Content="Maker" Command="{Binding MakerCommand}" />
            <Button Content="Analyzer" Command="{Binding AnalyzerCommand}" />
            <Button Content="Default" Command="{Binding DefaultCommand}" />
            <Button Content="Default" Command="{Binding DefaultCommand}" />
         </StackPanel>
        <ContentControl Grid.Row="1" Grid.ColumnSpan="3" Grid.RowSpan="2" Margin="20" prism:RegionManager.RegionName="ContentRegion" />
    </Grid>
</Window>

code behind: 主要是自定义增加文本框随着Log输出自从下拉功能

using System.Collections.Generic;
using System;
using System.Windows;
using System.Windows.Controls;

namespace TestUIForPrism.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

    }

    /// <summary>
    /// Attach a Property for Autoscrolling TextBox
    /// </summary>
    public class TextBoxBehaviour
    {
        static readonly Dictionary<TextBox, Capture> _associations = new Dictionary<TextBox, Capture>();

        public static bool GetScrollOnTextChanged(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(ScrollOnTextChangedProperty);
        }

        public static void SetScrollOnTextChanged(DependencyObject dependencyObject, bool value)
        {
            dependencyObject.SetValue(ScrollOnTextChangedProperty, value);
        }

        public static readonly DependencyProperty ScrollOnTextChangedProperty =
            DependencyProperty.RegisterAttached("ScrollOnTextChanged", typeof(bool), typeof(TextBoxBehaviour), new UIPropertyMetadata(false, OnScrollOnTextChanged));

        static void OnScrollOnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var textBox = dependencyObject as TextBox;
            if (textBox == null)
            {
                return;
            }
            bool oldValue = (bool)e.OldValue, newValue = (bool)e.NewValue;
            if (newValue == oldValue)
            {
                return;
            }
            if (newValue)
            {
                textBox.Loaded += TextBoxLoaded;
                textBox.Unloaded += TextBoxUnloaded;
            }
            else
            {
                textBox.Loaded -= TextBoxLoaded;
                textBox.Unloaded -= TextBoxUnloaded;
                if (_associations.ContainsKey(textBox))
                {
                    _associations[textBox].Dispose();
                }
            }
        }

        static void TextBoxUnloaded(object sender, RoutedEventArgs routedEventArgs)
        {
            var textBox = (TextBox)sender;
            _associations[textBox].Dispose();
            textBox.Unloaded -= TextBoxUnloaded;
        }

        static void TextBoxLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            var textBox = (TextBox)sender;
            textBox.Loaded -= TextBoxLoaded;
            _associations[textBox] = new Capture(textBox);
        }


        class Capture : IDisposable
        {
            private TextBox TextBox { get; set; }

            public Capture(TextBox textBox)
            {
                TextBox = textBox;
                TextBox.TextChanged += OnTextBoxOnTextChanged;
            }

            private void OnTextBoxOnTextChanged(object sender, TextChangedEventArgs args)
            {
                TextBox.ScrollToEnd();
            }

            public void Dispose()
            {
                TextBox.TextChanged -= OnTextBoxOnTextChanged;
            }
        }

    }

}

2.2 Maker.xaml

<UserControl x:Class="TestUIForPrism.Views.Maker"
             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:local="clr-namespace:TestUIForPrism.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="12*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Margin="10" Text="Before.csv Directory" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="0" Grid.Column="1" Margin="10" Text="{Binding PathConfig, Mode=TwoWay}"/>
        <Button Grid.Row="0" Grid.Column="2" Content="Reference" Margin="10" Command="{Binding CommandReference}">
            <Button.CommandParameter>config</Button.CommandParameter>
        </Button>
        <TextBlock Grid.Row="1" Grid.Column="0" Margin="10" Text="Input Directory" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1" Margin="10" Text="{Binding PathInput, Mode=TwoWay}"/>
        <Button Grid.Row="1" Grid.Column="2" Content="Reference" Margin="10" Command="{Binding CommandReference}">
            <Button.CommandParameter>input</Button.CommandParameter>
        </Button>
        <TextBlock Grid.Row="2" Grid.Column="0" Margin="10" Text="Output Directory" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="2" Grid.Column="1" Margin="10" Text="{Binding PathOutput, Mode=TwoWay}"/>
        <Button Grid.Row="2" Grid.Column="2" Content="Reference" Margin="10" Command="{Binding CommandReference}">
            <Button.CommandParameter>output</Button.CommandParameter>
        </Button>
        <Button Grid.Row="3" Grid.Column="0" Content="Start" Margin="10" Command="{Binding  CommandStart}"/>
        <TextBlock Grid.Row="4" Margin="1" Text="Log" />
        <TextBox Grid.Row="5" Grid.ColumnSpan="3" Text="{Binding Log}" local:TextBoxBehaviour.ScrollOnTextChanged="True" VerticalScrollBarVisibility="Auto"/>
    </Grid>
</UserControl>

2.3 Analyzer.xaml

<UserControl x:Class="TestUIForPrism.Views.Analyzer"
             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:local="clr-namespace:TestUIForPrism.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="400">
    <Grid Background="AliceBlue">
        
    </Grid>
</UserControl>

3 ViewModels

2.1 MainWindowViewModel.cs

using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using TestUIForPrism.Views;

namespace TestUIForPrism.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _title = "Please Name Tool";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        /// <summary>
        /// Region Navigation Controller in Prism Framework
        /// </summary>
        private readonly IRegionManager _regionManager;

        public DelegateCommand AnalyzerCommand { get; private set; }
        public DelegateCommand MakerCommand { get; private set; }

        public MainWindowViewModel(IRegionManager regionManager)
        {
            this._regionManager = regionManager;

            AnalyzerCommand = new DelegateCommand(Analyzer);
            MakerCommand = new DelegateCommand(Maker);
        }


        void Analyzer()
        {
            if (_regionManager != null)
            {
                _regionManager.RequestNavigate("ContentRegion", "Analyzer");
            }
        }

        void Maker()
        {
            if (_regionManager != null)
            {
                _regionManager.RequestNavigate("ContentRegion", "Maker");
            }
        }
    }
}

2.2 MakerViewModel.cs

using Microsoft.WindowsAPICodePack.Dialogs;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing.IndexedProperties;
using System.Text;
using System.Threading.Tasks;

namespace TestUIForPrism.ViewModels
{
    public class MakerViewModel : BindableBase
    {

        /// <summary>
        /// For showing log in TextBox
        /// </summary>
        private string log = @"";
        public string Log
        {
            get { return log; }
            set
            {
                this.SetProperty(ref this.log, value + Environment.NewLine);
            }
        }

        /// <summary>
        /// For showing path in TextBoxs
        /// </summary>
        private string pathconfig;
        public string PathConfig
        {
            get { return pathconfig; }
            set { SetProperty(ref pathconfig, value); }
        }

        private string pathinput;
        public string PathInput
        {
            get { return pathinput; }
            set 
            { 
              SetProperty(ref pathinput, value);
              CommandStart.RaiseCanExecuteChanged();
            }
        }

        private string pathoutput;
        public string PathOutput
        {
            get { return pathoutput; }
            set 
            { 
                SetProperty(ref pathoutput, value);
                CommandStart.RaiseCanExecuteChanged();
            }
        }


        /// <summary>
        /// For Start Button 
        /// </summary>
        private DelegateCommand _fieldStart;
        public DelegateCommand CommandStart =>
            _fieldStart ?? (_fieldStart = new DelegateCommand(ExecuteCommandStart, CanExecuteCommandStart));

        void ExecuteCommandStart()
        {
            // Test
            string TextExample = "Test log function ~";
            for (int i = 0; i < 100; i++)
            {
                this.Log += TextExample + " ==>  " + i;
            }
        }

        bool CanExecuteCommandStart()
        {
            if (string.IsNullOrEmpty(this.PathInput) || string.IsNullOrEmpty(this.PathOutput)) return false;
            return true;
        }

        /// <summary>
        /// For Reference Button
        /// </summary>
        private DelegateCommand<Object> _fieldReference;
        public DelegateCommand<Object> CommandReference =>
            _fieldReference ?? (_fieldReference = new DelegateCommand<Object>(ExecuteCommandReference, CanExecuteCommandReference));

        void ExecuteCommandReference(Object parameter)
        {
            string type = (string)parameter;

            if (type == "config")
            {
                this.PathConfig = @"..\..\TestUIForPrism\Config\Analizer.conf";
                System.Windows.MessageBox.Show($"{this.PathConfig} will been set automatically");
            }
            else
            {
                //Please install WindowsAPICodePack-Shell in Nuget
                using (var cofd = new CommonOpenFileDialog()
                {
                    Title = "Please Select  File",
                    InitialDirectory = @"",
                    IsFolderPicker = true,
                })
                {
                    if (cofd.ShowDialog() != CommonFileDialogResult.Ok)
                    {
                        return;
                    }
                    if (type == "input") this.PathInput = cofd.FileName;
                    else this.PathOutput = cofd.FileName;

                    System.Windows.MessageBox.Show($"{cofd.FileName} is Selected");
                }
            }

        }

        bool CanExecuteCommandReference(Object parameter)
        {
            return true;
        }
    }
}
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: WPF Prism框架是一个面向对象的框架,用于开发模块化、可扩展的WPF应用程序,它基于MVVM设计模式和依赖注入技术。该框架的主要目的是能够轻松地实现可插拔的模块,公共的服务、组件和工具类的共享,同时也提供了灵活的路由、事件聚合、模块加载、导航和命令处理等机制。使用WPF Prism框架可以快速地开发出灵活的WPF应用程序,从而提高代码质量和开发效率,减少代码的维护难度。 WPF Prism框架具有以下的特点: 1. 扩展性:可以轻松地添加新的模块、服务和组件,同时也可以快速替换现有的组件。 2. 可重用性:提供了丰富的公共组件、服务和工具类,从而可以提高代码的可重用性。 3. 灵活性:提供了灵活的路由、事件聚合、模块加载和导航等机制,能够更好地满足应用程序的需求。 4. 易用性:提供了一套完整的MVVM设计模式和依赖注入技术的实践方案,从而能够更好地组织应用程序的逻辑。 总之,WPF Prism框架是一个强大的工具,能够让我们更好地开发WPF应用程序,提高代码质量和开发效率,实现可插拔的模块化和可扩展性,同时也具有灵活性和易用性。 ### 回答2: WPF Prism框架是一种面向MVVM模式的开源框架,它帮助开发人员使用模块化的方式构建可扩展、可重用和易于维护的WPF应用程序。该框架主要由Microsoft和模式仲裁者团队开发和维护,它借鉴了许多现代的软件开发理念,比如IoC容器、依赖注入和事件聚合器等。 WPF Prism框架的核心思想是将应用程序分解为许多可独立维护和扩展的模块。这些模块可以基于业务逻辑、UI、数据或任何其他特征进行分组。在该框架,模块由各种名为“组件”的构建块组成。这些组件包括视图(View)、视图模型(ViewModel)、服务(Service)、模型(Model)等。通过基于这些组件的开发,可以实现具有高度可伸缩性和可重用性的应用程序。 为了实现这种模块化开发和组件化架构,WPF Prism框架提供了一些重要的工具和特性。例如,在该框架可以使用依赖注入容器(如Unity)来管理组件及其依赖关系。此外,该框架还提供了一些基于事件的消息机制,可方便地实现模块间的交互和通信。 总体来说,WPF Prism框架是一种利用开源技术实现企业级应用程序开发的最佳选择。它具有良好的模块化、组件化和可扩展性特性,可以在实现复杂WPF应用程序时提高开发效率和代码质量。 ### 回答3: WPF Prism是一个基于WPF框架,它为大型应用程序提供了一种组织、设计和部署的方式。它旨在帮助开发者构建可扩展、可维护和可测试的WPF应用程序。 WPF Prism采用了面向模块的编程思想,它将整个应用程序划分为多个模块,每个模块都包含自己的逻辑和用户界面。这种模块化设计使得应用程序易于扩展和维护,同时也简化了开发流程。 WPF Prism同时提供了一组强大的工具和功能,如依赖注入、命令模式和事件聚合等,这些功能让WPF应用程序更加易于开发和测试。它还提供了一个强大的导航和区域管理系统,开发者可以使用这些系统来管理不同部分的用户界面和功能。 总之,WPF Prism是一个优秀的框架,它为开发者提供了全面的工具和功能,使得构建WPF应用程序变得更加容易和高效。它的结构良好、可扩展性强,而且可以充分利用WPF的强大功能。无论是大型企业应用程序还是小型桌面应用程序,WPF Prism都是一个理想的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值