WPF etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
WPF etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

2 Temmuz 2018

WPF Logger Screen

Proje TreeView


  • Models
    • Log.cs
  • ViewModels
    • DelegateCommand.cs
    • LoggerConsoleViewModel.cs
    • MainWindowViewModel.cs
  • Views
    • LoggerConsoleView
    • MainWindow.xaml

Log.cs


using System;
using System.Collections.ObjectModel;
using System.Windows.Media;

namespace ConsoleLoggerDemo
{

    public class Logger
    {
        public static int Limit => 100;    
        public ObservableCollection Logs { get; private set; }
        public Logger()
        {
            Logs = new ObservableCollection();
        }
        public void Clear() => Logs.Clear();
        public void Add(ILoggable log)
        {
            if (Logs.Count == Limit)
                Logs.RemoveAt(0);
            Logs.Add(log);
        }
        public void Log(params string[] logs) => Add(new Log(logs));
        public void Error(params string[] logs) => Add(new Error(logs));
        public void Info(params string[] logs) => Add(new Info(logs));
        public void Success(params string[] logs) => Add(new Success(logs));
        public void Warning(params string[] logs) => Add(new Warning(logs));
    }

    public interface ILoggable
    {
        string Text { get; }
        SolidColorBrush Background { get; }
        SolidColorBrush Foreground { get; }
    }
    public class Log : ILoggable
    {
        public SolidColorBrush Background => Brushes.White;

        public SolidColorBrush Foreground => Brushes.Black;
        public string Text { get; private set; }
        public Log(params string[] logs)
        {
            string logText = $"Log({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }

    }
    public class Error : ILoggable
    {
        public SolidColorBrush Background => Brushes.Red;

        public SolidColorBrush Foreground => Brushes.White;
        public string Text { get; private set; }
        public Error(params string[] logs)
        {
            string logText = $"Error({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
    }
    public class Info : ILoggable
    {

        public string Text { get; private set; }
        public Info(params string[] logs)
        {
            string logText = $"Info({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.White;

        public SolidColorBrush Foreground => Brushes.Blue;
    }
    public class Success : ILoggable
    {
        public string Text { get; private set; }
        public Success(params string[] logs)
        {
            string logText = $"Success({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.Green;

        public SolidColorBrush Foreground => Brushes.White;
    }

    public class Warning : ILoggable
    {
        public string Text { get; private set; }
        public Warning(params string[] logs)
        {
            string logText = $"Warning({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.Orange;

        public SolidColorBrush Foreground => Brushes.White;
    }
}


DelegateCommand.cs
using System;
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class DelegateCommand : ICommand
    {
        private readonly Action _action;

        public DelegateCommand(Action action)
        {
            _action = action;
        }

        public void Execute(object parameter)
        {
            _action();
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged { add { } remove { } }
    }

}

LoggerConsoleViewModel
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class LoggerConsoleViewModel
    {
        public Logger Logger { get; private set; }
        public LoggerConsoleViewModel(Logger logger)
        {
            Logger = logger;
        }


        public ICommand ClearCommand {
            get {
                return new DelegateCommand(() =>
                {
                    Logger.Clear();
                });
            }
        }
    }
}

MainWindowViewModel.cs
using ConsoleLoggerDemo.Views;
using System;
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class MainWindowViewModel
    {
        public Logger logger { get; set; }
        public LoggerConsoleView Logger { get; private set; }

        public MainWindowViewModel()
        {
            logger = new Logger();
            Logger =

             new LoggerConsoleView(
                new LoggerConsoleViewModel(logger));
            logger.Log("Kayıt");
            logger.Info(Environment.MachineName);
            logger.Error("Hata");
            logger.Success("Basari");
            logger.Warning("Uyari");

            logger.Log("Kayıt");
            logger.Info("Bilgi");
            logger.Error("Hata");
            logger.Success("Basari");
            logger.Warning("Uyari");
        }
        public ICommand ErrorCommand {
            get {
                return new DelegateCommand(() =>
                {
                    try
                    {
                        int x = 0;
                        var z = 1 / x;

                    }
                    catch (Exception ex)
                    {

                        logger.Error(ex.ToString());
                    }
                });
            }
        }
        public ICommand InfoCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Info("some info text");
                });
            }
        }
        public ICommand WarningCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Warning("some warning text");
                });
            }
        }
        public ICommand LogCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Log("some log text");
                });
            }
        }
        public ICommand SuccessCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Success("some success text");
                });
            }
        }
    }
}

LoggerConsoleView.xaml

<Page x:Class="ConsoleLoggerDemo.Views.LoggerConsoleView"
      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:ConsoleLoggerDemo"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
      Title="LoggerConsole">
    <Border BorderThickness="1" BorderBrush="Black" Padding="4">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal" Background="LightGray">
                <Button Content="Clear" Margin="4" Padding="4"
Command="{Binding ClearCommand}"/>
            </StackPanel>
            <ScrollViewer Margin="0" Background="White" Grid.Row="1" Name="Scroll">
                <StackPanel>
                    <ItemsControl  ItemsSource="{Binding Logger.Logs,Mode=OneWay}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Text,Mode=OneWay}"
Foreground="{Binding Foreground}" FontFamily="Consolas"
Background="{Binding Background}" Margin="2"
TextWrapping="Wrap" Padding="4" BorderThickness="0"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Border>
</Page>


LoggerConsoleView.xaml.cs
using ConsoleLoggerDemo.ViewModels;
using System.Windows.Controls;

namespace ConsoleLoggerDemo.Views
{
    public partial class LoggerConsoleView : Page
    {
        public LoggerConsoleView(LoggerConsoleViewModel loggerConsoleViewModel)
        {
            InitializeComponent();
            DataContext = loggerConsoleViewModel;
            loggerConsoleViewModel.Logger.Logs.CollectionChanged += (se, ev) =>
            {
                Scroll.ScrollToBottom();
            };
        }
    }
}

MainWindow.xaml
<Window x:Class="ConsoleLoggerDemo.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:ConsoleLoggerDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="600">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="100"/>
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Padding" Value="4"/>
            <Setter Property="FontWeight" Value="Bold"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Button Content="Error" Background="Red"
Command="{Binding ErrorCommand}"/>
            <Button Content="Info" Background="SkyBlue"
Command="{Binding InfoCommand}"/>
            <Button Content="Success" Background="DarkSeaGreen"
Command="{Binding SuccessCommand}"/>
            <Button Content="Warning" Background="Orange"
Command="{Binding WarningCommand}"/>
            <Button Content="Log" Background="White"
Command="{Binding LogCommand}"/>
        </StackPanel>
        <Frame Content="{Binding Logger}" Grid.Row="1"/>

    </Grid>
</Window>

MainWindow.xaml
using ConsoleLoggerDemo.ViewModels;
using System.Windows;

namespace ConsoleLoggerDemo.Views
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        MainWindowViewModel model { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            model = new MainWindowViewModel();
            DataContext = model;
        }       
    }
}


5 Aralık 2017

WPF Notification (Desktop Alert, Toast)

Notifications.Wpf paketini kullanarak notification paketi kullanımının yönergeleri ve örnek proje  aşağıda ki adreste yer alıyor.

https://github.com/Federerer/Notifications.Wpf


Burada MVVM modeli için güzel bir örnek var. Ben MVVM kullanmadan standart özelleştirilmiş bir notification yapımını göstereceğim.

1. Notifications.Wpf paketini projemize nuget ile ekleyelim.

2. NotificationView adında bir User Control ekleyelim.

3. NotificationView.xaml içerisine aşağıdaki xmlns ekleyelim.

xmlns:controls="clr-namespace:Notifications.Wpf.Controls;assembly=Notifications.Wpf"

Ayrıca notification kapatmak için button içerisine  controls:Notification.CloseOnClick="True"
property eklendi. Yani bu butona basıldığı zaman Notification kapatılacak.

4. NotificationView.cs içerisine aşağıdaki kodları ekleyin
     
        private readonly INotificationManager _manager;
        public string Title { get; set; }
        public string Message { get; set; }


        public NotificationView(INotificationManager manager)
        {
            InitializeComponent();
             _manager = manager;

        }

5. Açmak için is MainWindows içerisinde aşağıdaki NotifcationManager tanımlayalım.

private NotificationManager notificationManager;

MainControl() constructor içerisinde notificationManager'ın bir örneğini oluşturalım

notificationManager = new NotificationManager();


Daha sonra notification ile göstermek için

 var content = new NotificationView(notificationManager);

ile gösterilecek notification oluşturulur.

notificationManager.Show(content, expirationTime: TimeSpan.FromSeconds(30));

metodu ile gösterilir.



MainWindow.xaml

<Window x:Class="DesktopNotificationApp.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:DesktopNotificationApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="auto" Width="291.231">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition MinHeight="50" Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Content="Bildirim Göster" Click="Button_Click"/>
        <ListBox x:Name="lbSecimler" Grid.Row="1"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using Notifications.Wpf;
using System;
using System.Collections.Generic;
using System.Windows;

namespace DesktopNotificationApp
{
    public partial class MainWindow : Window
    {
        private NotificationManager notificationManager;
        public MainWindow()
        {
            InitializeComponent();
            notificationManager = new NotificationManager();
        }
        int titleNumber;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var content = new NotificationView(notificationManager);
            content.txbTitle.Text = $"{++titleNumber}. Başlık";
            content.txbMessage.Text = $"{titleNumber}. Mesaj";
            content.cmbSelectAnswer.ItemsSource = new List<string>()
            {
               $"Test A{titleNumber}",
               $"Test B{titleNumber}",
            };

            notificationManager.Show(content, expirationTime: TimeSpan.FromSeconds(30));
        }
    }
}

NotificationView.xaml

<UserControl x:Class="DesktopNotificationApp.NotificationView"
             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:DesktopNotificationApp"
             xmlns:controls="clr-namespace:Notifications.Wpf.Controls;assembly=Notifications.Wpf"
             mc:Ignorable="d" Height="172.388" Width="auto">
    <Grid Background="LightSkyBlue">
        <Grid.RowDefinitions>
            <RowDefinition MinHeight="40" Height="auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition MinHeight="40" Height="auto"/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="txbTitle" FontSize="20" FontWeight="Medium" Foreground="Black"/>
        <Grid Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="txbMessage" FontSize="12" FontWeight="Medium" Background="White" Foreground="Black" TextWrapping="Wrap"/>
            <ComboBox x:Name="cmbSelectAnswer" Grid.Row="1" SelectedIndex="0"/>
        </Grid>
        <UniformGrid Grid.Row="2" Columns="2">
            <Button Content="KAPAT"  controls:Notification.CloseOnClick="True" Click="Dismiss"/>
            <Button Content="SEÇ"  controls:Notification.CloseOnClick="True" Grid.Column="1" Click="Select"/>
        </UniformGrid>
    </Grid>
</UserControl>

NotificationView.xaml.cs

using Notifications.Wpf;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace DesktopNotificationApp
{
    public partial class NotificationView : UserControl
    {
        private readonly INotificationManager _manager;
        private MainWindow mainWindow => Application.Current.Windows.OfType<MainWindow>().Single();
      
        public string Title { get; set; }
        public string Message { get; set; }

        public NotificationView(INotificationManager manager)
        {
            InitializeComponent();
            _manager = manager;
        }

        private void Dismiss(object sender, RoutedEventArgs e)
        {
            var text = $"{txbTitle.Text} seçim yapılmadı.";
            mainWindow.lbSecimler.Items.Add(new ListBoxItem() { Content = text });
        }

        private void Select(object sender, RoutedEventArgs e)
        {
            var text = cmbSelectAnswer.Text;
            mainWindow.lbSecimler.Items.Add(new ListBoxItem() { Content = text });
        }
    }
}