Understanding Commands in WPF: A Cleaner Alternative to Button Click Events

Many WPF developers start by using Button Click events for handling user actions. At first, this seems simple and straightforward. But very soon, the code-behind file becomes huge , and maintaining it turns into a challenge. One big problem arises: when the logic changes, the button does not enable or disable automatically , and testing button click logic becomes very difficult. So the big question is: Is there a better way to handle button actions in WPF? The answer is Commands . In this post, we’ll learn how to use Commands in WPF with a simple, practical example. We’ll cover: What a Command is How it works Why using Commands is better than Click events How buttons can automatically enable or disable based on conditions What is a Command in WPF? In WPF, a Command acts as a middle layer between the UI and your logic. Instead of the button directly calling a method, it triggers a Command , and the Command decides: What code should run Whether the button s...

How to Create TabControl using Prism Region


MainWindow

<metro:MetroWindow x:Class="PrismDemo.Views.MainWindow"
        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:PrismDemo.Views"
        mc:Ignorable="d" xmlns:prism="http://prismlibrary.com/"
        Title="MetroPrismDemo"
        xmlns:metro="http://metro.mahapps.com/winfx/xaml/controls">

    <Grid>
        <TabControl Margin="5" prism:RegionManager.RegionName="TabRegion"
                  VerticalAlignment="Stretch" HorizontalAlignment="Left" BorderThickness="0">
        </TabControl>
    </Grid>
</metro:MetroWindow>

TabControlAdapter  [Custom Adapter ]

 class TabControlAdapter : RegionAdapterBase<TabControl>
    {
        public TabControlAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
        {
        }

        protected override void Adapt(IRegion region, TabControl regionTarget)
        {
            region.Views.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                    foreach (UserControl item in e.NewItems)
                    {
                        regionTarget.Items.Add(new TabItem { Header = item.Name, Content = item });
                    }
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                    foreach (UserControl item in e.OldItems)
                    {
                        var tabTodelete = regionTarget.Items.OfType<TabItem>().FirstOrDefault(n => n.Content == item);
                        regionTarget.Items.Remove(tabTodelete);
                    }

            };
        }


        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }

MainModule 

 public class MainModule : IModule
    {
        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
         
        }

        public void OnInitialized(IContainerProvider containerProvider)
        {
            var regionManager = containerProvider.Resolve<IRegionManager>();
            regionManager.RegisterViewWithRegion("TabRegion", typeof(Info));
            regionManager.RegisterViewWithRegion("TabRegion", typeof(Warning));
            regionManager.RegisterViewWithRegion("TabRegion", typeof(Error));
        }
    }
App.xaml.cs

 public partial class App
    {
     
        protected override Window CreateShell()
        {
            var shell = Container.Resolve<MainWindow>();
            return shell;
        }
        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
            regionAdapterMappings.RegisterMapping(typeof(TabControl), Container.Resolve<TabControlAdapter>());
        }
        protected override IModuleCatalog CreateModuleCatalog()
        {
            var module = base.CreateModuleCatalog();
            module.AddModule<MainModule>();
            return module;
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
         
        }
    }

Comments

  1. hi,
    great solution. if i understood you, the 3 tabs are added on initialization.
    Is there a way to add them dynamically?

    ReplyDelete
    Replies
    1. Thanks
      Yes there is way to add tabitem dynamically

      Delete
    2. how can i add them dynamically?

      Delete
    3. you can follow this video https://youtu.be/JvJweEdjZ5g?si=HGmcw71562Z8BivA

      Delete

Post a Comment

Popular posts from this blog

Filter DataGrid and ListView in wpf using ICollectionView

Pagination of DataGrid in WPF using MVVM