'WPF'에 해당되는 글 31건

  1. 2025.03.17 터치 스크롤 뷰어 List
  2. 2023.06.09 [WPF] 체크박스 xName을 이용하여 반복작업 하지 않고 간결하게
  3. 2023.06.08 MEF란?
  4. 2023.06.07 [WPF] gRPC Client 빌드 안될때 대처법
  5. 2022.12.05 dynamic property 에서 Set을 할떄
  6. 2021.11.18 2개의 LIST 비교 하는것
  7. 2020.03.06 WPF TabControl에서 SelectionChanged가 계속 호출되는 문제
  8. 2019.03.21 list depp copy , clone 하는 간단한 방법
  9. 2019.02.26 OpenCV, Face API를 이용해서 얼굴 검출하기 2번째
  10. 2019.01.22 리스트에 빈칸없이 꽉 차게 넣는 로직 알고리즘
  11. 2018.11.13 라디오 컨트롤 바인딩
  12. 2018.08.31 WPF Title Icon 제거하기
  13. 2018.08.29 WPF 강제 소프트웨어 렌더링 설정
  14. 2018.08.07 ViewBox에서 폰트사이즈 고정하기
  15. 2018.05.02 WPF에서 GIF 돌리기 컨트롤 1
  16. 2018.03.07 Xaml에 Binding을 하지 않고 컨버터를 쓰고 싶을때
  17. 2018.03.07 Style안에서 ConverterParameter를 Binding 하기
  18. 2018.01.02 WPF에서 MiniDump 뜨는법
  19. 2017.11.24 c++ DLL에서 예외 오류 잡는법
  20. 2017.09.12 Listview , Button MouseOver, Selcted Color 제거
  21. 2017.09.06 Converter를 쓰지 않고 바인딩된 TextBlock에 글자를 추가하고 싶을때
  22. 2017.08.08 MVVM 하위 컨트롤 바인딩
  23. 2017.08.07 해상도에 따른 이미지 크기 변경
  24. 2017.07.17 [WPF] NavagionManager
  25. 2016.06.08 [WPF] IsolatedStorageManager
  26. 2016.04.19 Image Filter 사용하기 (이미지 프로세싱)
  27. 2016.04.14 WPF HtmlToXaml에 Image Add하기
  28. 2016.04.04 CustomControl ImageButton
  29. 2011.05.27 [Surface] FlowDocument 사용하기
  30. 2011.05.19 [surface] WPF에서 VisualState 쓰기
wpf2025. 3. 17. 16:49

ListView안의 List에서는 터치가 안먹는다. 이떄는 

<ListView ItemsSource="{Binding ElementName=xMainPage , Path=DataContext.AllMenuFlipData}">
    <ListView.Template>
        <ControlTemplate>
            <StackPanel IsItemsHost="True" />
        </ControlTemplate>
    </ListView.Template>

 

이런식으로 Template안의 Panel에서 IsItemHost 를 True로 바꿔주면 된다.

 

GPT에선

IsItemsHost 속성은 주로 **Panel**에서 사용되며, 이 속성이 **true**로 설정된 경우 해당 패널이 항목을 호스트하는 역할을 한다는 것을 의미합니다.

 

이렇게 할경우 list에서 스크롤할떄 전체로 스크롤 된다.

 

키오스크 개발할떄 필수인거 같다.!! 

 

Posted by 동동(이재동)
wpf2023. 6. 9. 18:37

 private void MessageCheck_Checked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded == false)
                return;

            var name = (sender as ToggleButton).Name;

            var ctl = xGroups.FindName(name) as ToggleButton;

            DataManager.LocalData.MessageSelect.GetType().GetProperty(name.Remove(0, 1)).SetValue(DataManager.LocalData.MessageSelect, ctl.IsChecked);

            DataManager.Instance.SaveData();
        }

        private void TelegramMessageSelectPage_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((e.NewValue) as bool? == false)
                return;

            foreach (var item in DataManager.LocalData.MessageSelect.GetType().GetProperties())
            {
                var ctl = xGroups.FindName($"x{item.Name}") as ToggleButton;

                if (ctl != null)
                    ctl.IsChecked = (bool)item.GetValue(DataManager.LocalData.MessageSelect);
            }
        }

 

 public class MessageSelectModel
    {
        public bool IsDeepSleep { get; set; }

        public bool IsStartEndMap { get; set; }

        public bool IsDriveEnd { get; set; }
    }

 

 

 

그냥 바인딩하는게 최고지만 피지 못할경우에는 

 xIsAutoAfterBlowBtn.IsChecked = DataManager.LocalData.IsAutoAfterBlow; <-이런식으로 노가다 작업하지말고

 

xName이랑 프로퍼티랑 이름을 같게해서 반복작업을 줄여보자

'wpf' 카테고리의 다른 글

터치 스크롤 뷰어 List  (0) 2025.03.17
listbox에서 터치스크롤시 화면 전체가 움직일떄  (0) 2025.01.07
MEF란?  (0) 2023.06.08
[WPF] gRPC Client 빌드 안될때 대처법  (0) 2023.06.07
dynamic property 에서 Set을 할떄  (0) 2022.12.05
Posted by 동동(이재동)
wpf2023. 6. 8. 14:50

https://blog.powerumc.kr/189

 

[MEF] 1. Managed Extensibility Framework 이란?

MEF (Managed Extensibility Framework) 란? Menaged Extension Framewkr(이하 MEF) 란? 가장 쉽게 얘기하자면, 어플리케이션과 컴포넌트의 재사용성을 높일 수 있는 프레임워크입니다. 기존의 어플리케이션은 하나

blog.powerumc.kr

 

여기에 잘정리 되어 있으니 보자..

 

Menaged Extension Framewkr(이하 MEF) 란? 가장 쉽게 얘기하자면, 어플리케이션과 컴포넌트의 재사용성을 높일 수 있는 프레임워크입니다. 기존의 어플리케이션은 하나의 목적을 하나의 어플리케이션으로 구현한 정적인(Statically) 어플리케이션이라면, MEF 는 보다 동적인(Dynamically) 어플리케이션을 구축할 수 있는 새로운 라이브러리를 제공합니다.

Posted by 동동(이재동)
wpf2023. 6. 7. 15:25

서버야 프로젝트 템플릿이 있어서 그냥 자동으로 만들어지지만

WPF client에서 Protos에 greet.proto를 복사하고 따라했지만 빌드에러가 났다..

 

구글 검색후 해결했다

 

https://stackoverflow.com/questions/60810497/grpc-erros-in-wpf-net-core

 

gRPC erros in WPF .NET Core

I want to create a simple WPF Core, gRPC project. This "code" works perfectly in my .NET Core Console app, however WPF seems to be something special. Proto File syntax = "proto3"...

stackoverflow.com

 

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
    <CoreCompileDependsOn>$(CoreCompileDependsOn);Protobuf_Compile</CoreCompileDependsOn>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.23.2" />
    <PackageReference Include="Grpc.Net.Client" Version="2.53.0" />
    <PackageReference Include="Grpc.Tools" Version="2.54.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
    
  </ItemGroup>

</Project>

 

프로젝트 편집에서

 

<CoreCompileDependsOn>$(CoreCompileDependsOn);Protobuf_Compile</CoreCompileDependsOn>

이걸 추가함으로써 빌드가 되었다.

 

 

'wpf' 카테고리의 다른 글

[WPF] 체크박스 xName을 이용하여 반복작업 하지 않고 간결하게  (0) 2023.06.09
MEF란?  (0) 2023.06.08
dynamic property 에서 Set을 할떄  (0) 2022.12.05
public (string name, int age) GetUser()  (0) 2022.10.26
PeriodicTimer  (0) 2022.08.31
Posted by 동동(이재동)
wpf2022. 12. 5. 11:44

await SendConfirmMsg(msgSplit, DataManager.LocalData.LongTrendBuy, "QuitRange");

 

 

 

private static async Task SendConfirmMsg(string[] msgSplit, dynamic data, string prop)
        {
            double numValue;
            bool isNum = double.TryParse(msgSplit[2], out numValue);

            data.GetType().GetProperty(prop).SetValue(data, numValue, null);           

            DataManager.Instance.SaveData();
            await TelegramPushService.SendMessage($"{msgSplit[0]} {msgSplit[1]} {numValue}");
        }

 

 

이런식으로 반복되는 구문을 dynamic을 이용해서 짧게 만들수 있다.

 

중요

 

data.GetType().GetProperty(prop).SetValue(data, numValue, null);   

 

참고

https://stackoverflow.com/questions/12970353/c-sharp-dynamically-set-property

'wpf' 카테고리의 다른 글

MEF란?  (0) 2023.06.08
[WPF] gRPC Client 빌드 안될때 대처법  (0) 2023.06.07
public (string name, int age) GetUser()  (0) 2022.10.26
PeriodicTimer  (0) 2022.08.31
2개의 LIST 비교 하는것  (0) 2021.11.18
Posted by 동동(이재동)
wpf2021. 11. 18. 18:01

private bool IsDiffList<T>(List<T> list1, List<T> list2)
        {
            var diff1 = list1.Except(list2);
            var diff2 = list2.Except(list1);

            var resultDiff = diff1.Concat(diff2).ToList();

            if (resultDiff.Count > 0)
                return true;
            else
                return false;
        }

 

if (IsDiffList<OrderInfo>((xProfitOrderListbox.ItemsSource as List<OrderInfo>).ToList(), _service.OrderInfoList))
                {
                    xProfitOrderListbox.ItemsSource = _service.OrderInfoList;
                    xProfitOrderListbox.Items.Refresh();
                }

 

이런식으로 반복적으로 item을 넣어야 하는곳에 넣어준다. timer를 이용하면 객체를 계속 생성하기때문에

 

무조건 넣어주면 메모리 Leak 이 걸린다. 그렇기 떄문에 변경될때만 적용되게 해야한다.

'wpf' 카테고리의 다른 글

public (string name, int age) GetUser()  (0) 2022.10.26
PeriodicTimer  (0) 2022.08.31
싱글톤 쓰기  (0) 2021.08.24
Combox 에 Enum 바인딩  (0) 2021.05.06
WPF에서 기본적으로 제공해주는 BoolToVisConverter 컨버터  (0) 2020.04.28
Posted by 동동(이재동)
wpf2020. 3. 6. 17:53

WPF에서 텝이 변결될 때 발생하는 이벤트 키워드인 SelectionChanged를 TabControl에 사용해서 탭을 가져오는 형태로 코드구성을 진행하는 중 이상한 점이 발견됬다.

내가 만드는 프로그램에서는 2번째 탭을 클릭하면 SelectionChanged가 호출 되고 2번째 탭 내의 ListBox 컨텐츠가 업데이트 되는 형식으로 코드가 진행될 것으로 예상하고 디버그를 하였으나, 실제로는 2번째 탭을 클릭하면 SelectionChanged가 재귀적으로 무한호출 되버리는 문제가 발생되었다.

문제는 TabControl 내부에 컨텐츠가 업데이트 되거나 무슨 변화가 존재할 경우에도 해당 이벤트가 호출된다는 점이다. 이럴 대는 Source 값이 TabControl인지 비교하는 항목이 추가되야 하며 아래와 같은 코드구성이 가능하다.

private void MainTabChanged(object sender, SelectionChangedEventArgs e)
{
int tabItem = ((sender as TabControl)).SelectedIndex;
if (e.Source is TabControl) // This is a soultion of those problem.
{
switch (tabItem)
{
case 0: // Chatting
Debug.WriteLine("Tab: Chatting");
if (MainChatList.Items.Count > 0)
{
MainChatList.SelectedIndex = MainChatList.Items.Count - 1;
MainChatList.ScrollIntoView(MainChatList.Items[MainChatList.Items.Count - 1]);
}
break;
case 1: // Users
Debug.WriteLine("Tab: Users");
break;
case 2: // Friends
Debug.WriteLine("Tab: Friends");
this.OnFriendTabActive();
break;
default:
Debug.WriteLine("Tab: " + tabItem);
break;
}
}
}

 

소스의 4번째 줄을 확인하면 TabControl의 문제점을 개선하는 코드를 확인 할 수 있다.

 

 

if (e.Source is TabControl)<--로 확인가능

Posted by 동동(이재동)
wpf2019. 3. 21. 17:44

List를 그대로 대입시켜버리면 해당 객체가 바뀌기때문에


clone, deep copy를 해야한다.


List<Book> books_2 = books_1.ConvertAll(book => new Book());



내가 봤을때는 이게 가장 나은 방법같다.

https://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt

Posted by 동동(이재동)
wpf2019. 2. 26. 16:56

얼굴 인식 2번쨰

Face API를 항상 호출하면 1분에 20번(무료 버전 기준) 호출 제한을 넘기때문에

일단 openCV 에서 얼굴을 최대한 감지한후 호출을 해야 호출 제한에 어느정도 자유롭다.

일단 openCVSharp을 설치하면

CascadeClassifier class의 DetactMultiScale을 이용해서 사람 얼굴을 감지할수 있다.

private readonly CascadeClassifier _localFaceDetector = new CascadeClassifier();
_localFaceDetector.Load("Data/haarcascade_frontalface_alt.xml");

_grabber.NewFrameProvided += (s, e) =>
{
var rects = _localFaceDetector.DetectMultiScale(e.Frame.Image, 1.3, 1, 0, new OpenCvSharp.Size(200, 200));
.
.
//Face API를 이용해서 얼굴 찾기

이런식으로 1차적으로 openCV 얼굴 검출 2차 Face API를 이용해서 얼굴 찾기 하면 된다.

프레임별로 얼굴을 찾는 부분을 호출 하기 때문에 2초 정도 안에는 다시 FaceAPI를 호출하지 못하도록 구현해야한다.


DetectMultiScale을 이용해서 검출할수 있는 최대 인원 및 최소 사이즈를 설정할수 있다. 샘플에서는 얼굴 크기가 200 이상인사람만 찾도록 구현했다.

샘플은 웹캠이 구동되고 얼굴을 비추면 첨보는 사람면 등록을 , 등록된 사람이면 userData의 이름 및 성별등등을 출력해준다. Face API는 최대한 호출되지 않도록 openCV에서 얼굴이 완전히 검출 되었을때만 사용했다.


FaceApiTest2.zip













Posted by 동동(이재동)
wpf2019. 1. 22. 16:37


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        private int index = 0;
        private ObservableCollection<FranchiseModel> list = new ObservableCollection<FranchiseModel>();
 
        public void Next()
        {
            list.Clear();
 
            while (list.Count < 3)
            {
                list.Add(Data[index]);
                index++;
 
                if (index >= Data.Count)
                {
                    index = 0;
                }
            }
 
            FranchiseLists = list;
        }



예를들어 Data에는 10개의 값이 있고 


list에는 3개씩 꽉차게 보여주고 싶다 하면


인덱스를 봤을때

0,1,2 3,4,5 6,7,8 9,10,0


이렇게 10개가 찼을때 다시 젤첨의 0번째 인덱스를 보여주게 함으로써 빈값이 없게 만든다.


list를 항아리라 생각하면 쉽다. while문을 돌면서 무조건 3개를 차게 한다.


이렇게 하면 만약 항상 list는 3개가 되기때문에 빈칸없는 정보를 보여줄때 쓰면 좋다.



Posted by 동동(이재동)
wpf2018. 11. 13. 16:20


namespace WpfRadioButton
{
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Markup;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ViewModel vm = new ViewModel();
        public MainWindow()
        {
            InitializeComponent();

            DataContext = vm;
        }
    }

    [ValueConversion(typeof(bool), typeof(Enum))]
    public class EnumToBoolExtension : MarkupExtensionIValueConverter
    {
        #region IValueConverter
        
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return parameter.Equals(value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return ((bool) value) == true ? parameter : DependencyProperty.UnsetValue;
        }

        #endregion

        #region MarkupExtension

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        #endregion
    }

    public enum Direction
    {
           North,
        Easth,
        West,
        South
    }

    public class ViewModel : INotifyPropertyChanged
    {
        public Direction direction;

        public Direction Direction
        {
            get
            {
                return this.direction;
            }

            set
            {
                this.direction = value;
                this.RaisePropertyChanged("Direction");
            }
        }

        #region NotifyPropertyChanged Methods

        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}


<Window x:Class="WpfRadioButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:WpfRadioButton"
        Title="RadioButton" Height="200" Width="300">
    <Grid DataContext="{Binding}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <RadioButton Grid.Row="0" GroupName="directionText" Margin="5" VerticalAlignment="Center" Content="North" 
                     IsChecked="{Binding Direction, Converter={local:EnumToBool}, ConverterParameter={x:Static local:Direction.North}}"/>
        <RadioButton Grid.Row="1" GroupName="directionText" Margin="5" VerticalAlignment="Center" Content="East" 
                     IsChecked="{Binding Direction, Converter={local:EnumToBool}, ConverterParameter={x:Static local:Direction.Easth}}"/>
        <RadioButton Grid.Row="2" GroupName="directionText" Margin="5" VerticalAlignment="Center" Content="West" 
                     IsChecked="{Binding Direction, Converter={local:EnumToBool}, ConverterParameter={x:Static local:Direction.West}}"/>
        <RadioButton Grid.Row="3" GroupName="directionText" Margin="5" VerticalAlignment="Center" Content="South" 
                     IsChecked="{Binding Direction, Converter={local:EnumToBool}, ConverterParameter={x:Static local:Direction.South}}"/>
        <TextBlock Grid.Row="4" Margin="5" VerticalAlignment="Center" Text="{Binding Direction}"/>
    </Grid>
</Window>

출처 : https://zamjad.wordpress.com/2014/03/01/radio-button-in-mvvm/

Posted by 동동(이재동)
wpf2018. 8. 31. 12:53
public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
 
        protected override void OnSourceInitialized(EventArgs e)
        {
            IconHelper.RemoveIcon(this);
        }
    }



public static class IconHelper
    {
        [DllImport("user32.dll")]
        static extern int GetWindowLong(IntPtr hwnd, int index);
 
        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
 
        [DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, 
                   int x, int y, int width, int height, uint flags);
 
        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hwnd, uint msg, 
                   IntPtr wParam, IntPtr lParam);
 
        const int GWL_EXSTYLE = -20;
        const int WS_EX_DLGMODALFRAME = 0x0001;
        const int SWP_NOSIZE = 0x0001;
        const int SWP_NOMOVE = 0x0002;
        const int SWP_NOZORDER = 0x0004;
        const int SWP_FRAMECHANGED = 0x0020;
        const uint WM_SETICON = 0x0080;
 
        public static void RemoveIcon(Window window)
        {
            // Get this window's handle
            IntPtr hwnd = new WindowInteropHelper(window).Handle;
 
            // Change the extended window style to not show a window icon
            int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
            SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);
 
            // Update the window's non-client area to reflect the changes
            SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | 
                  SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
        }
 
    }


Posted by 동동(이재동)
wpf2018. 8. 29. 17:25

app.xaml.cs 에서 onStartup에서 


RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;


렌더모드를 소프트웨어 온리로 바꿨더니


Mediaelement 의 4k GPU 사용량이 100에서 많이 줄어들었다.


DID같은경우는 너무 GPU가 높으니 하드웨어 렌더링보다는 소프트웨어 렌더링을 이용해야겠다.



참고 : https://blogs.msdn.microsoft.com/jgoldb/2010/06/22/software-rendering-usage-in-wpf/



Posted by 동동(이재동)
wpf2018. 8. 7. 12:23
<Viewbox StretchDirection="DownOnly" >
     <Label Content="Enable" FontSize="10" FontStretch="Normal" />
</Viewbox>


Posted by 동동(이재동)
wpf2018. 5. 2. 17:34


샘플 소스 참조~


WpfAnimatedGif-master.zip


Posted by 동동(이재동)
wpf2018. 3. 7. 17:34

대부분 컨버터는 바인딩을 걸고 쓰지만 아래와 같이 영문버전 한글버전 식으로 컨버터를 쓰고 싶다면

이미지소스 에 바인딩을 걸어 버리면 된다.



1
2
3
4
5
 <Image  Stretch="None" Visibility="{Binding IsShowInfoWordImage, Converter={StaticResource BoolToVisibilityConverter}}">
                        <Image.Source>
                            <Binding Source="/BANAPRESSO_KIOSK;component/Images/order_list_info_words.png" Converter="{StaticResource GlobalImageNameConverter}" />
                        </Image.Source>
</Image>

Posted by 동동(이재동)
wpf2018. 3. 7. 14:34

ConvererParameter에는 바인딩을 걸지 못한다.


그래서 사용할수 있는방법은 멀티 바인딩을 이용하면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
 public class GlobalImageNameConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var temp = values[0];
            return values[0];
        }
 
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


이런식으로 IMultiValueConverter Interface를 구축한후


Style안에는


1
2
3
4
5
6
7
8
  <Image x:Name="img" Stretch="None">
                            <Image.Source>
                                <MultiBinding Converter="{StaticResource GlobalImageNameConverter}">
                                    <Binding Path="NormalImage" RelativeSource="{RelativeSource TemplatedParent}" />
                                    <Binding Path="IsDisable" RelativeSource="{RelativeSource TemplatedParent}" />
                                </MultiBinding>
                            </Image.Source>
  </Image>

이렇게 구현했다.


 RelativeSource="{RelativeSource TemplatedParent}" 이부분은 templatebinding이라서 넣은것이고 일반 바인딩일경우에는 없앤다.



Posted by 동동(이재동)
wpf2018. 1. 2. 19:05

간략한 소스


MiniDump.cs


wpf에서는 

 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


으로 했을시에 작동한다.

첨에 모르고 

this.DispatcherUnhandledException += App_DispatcherUnhandledException;


이렇게 했는데 계속 0kb 로 덤프가 안떠져서 삽질을...


덤프가 만들어지면


1. exe 실행파일

2. pdb 파일

3. dmp  파일


3개 파일을 한 폴더에 넣고 dmp 클릭후 비쥬얼 스튜디오에서 혼합으로 디버그를 선택하면 오류난 위치를 알려준다.



Posted by 동동(이재동)
wpf2017. 11. 24. 17:22


C++에서 사용하는 DLL에서 오류가 나면 try catch에서 잡히지 않는문제를 해결 하였다.




AccessViolationException 예외는 네이티브 쪽에서 메모리 접근 위반을 했을 때 발생 하는 예외 이다.

할당되지 않은 메모리 또는 코드가 접근 권을 갖지 않는 메모리를 읽거나 쓰기를 시도하면 네이티브 코드(언 세이프 코드)에서 액세스 위반이 발생한다.

 

그러나 보통 System.Exception의 파생 클래스인 셈이라서 catch에서 이 예외를 포착할 것으로 생각하지만 애플리케이션은 이 예외를 잡지 못해서 이상 종료를 한다.

 

.NET Framework 3.5 이전에는 AccessViolationException을 catch 할 수 있었지만 .NET Framework 4 이후에서는 못하도록 바뀌었다.

 

이 예외를 잡고 싶다면 두 가지 방법을 하나를 하면 된다.

1. HandleProcessCorruptedStateExceptionsAttribute

AccessViolationException을 catch 하고 싶은 메소드에HandleProcessCorruptedStateExceptionsAttribute를 붙여서 잡을 수 있다.

[HandleProcessCorruptedStateExceptions]

void DoSomething()

{

try {

AccessViolationException를 발생하는();

} catch(AccessViolationException e) {

//---포착 가능

}

}

 

 

2.legacyCorruptedStateExceptionsPolicy

하위 호환성 때문에 기존(.NET Framework 3.5 이전)처럼 애플리케이션 전체에서 포착할 수 있도록 하고 싶은 경우. 구성 파일(*. config)에<legacyCorruptedStateExceptionsPolicy>요소를 넣어서 해결할 수 있다.

<configuration>

<runtime>

<legacyCorruptedStateExceptionsPolicy enabled="true"/>

</runtime>

</configuration>

 

 

출처: http://blog.xin9le.net/entry/2015/07/22/053738

Posted by 동동(이재동)
wpf2017. 9. 12. 12:40

listview
1
2
3
4
5
6
7
8
9
10
11
12
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListViewItem}">
                        <Setter Property="Background" Value="Transparent" />
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ListViewItem}">
                                    <ContentPresenter />
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ListView.ItemContainerStyle>


button


1
2
3
4
5
6
7
8
9
10
11
12
13
14
 <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Button}">
                                <Border Background="{TemplateBinding Background}">
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
</Button.Style>


Posted by 동동(이재동)
wpf2017. 9. 6. 12:13

예를 들면 3이라는 숫자가 바인딩 되어 있고

이걸 3개월로 바꾸고 싶으면 Converter를 쓰면 되지만 일일이 만들기가 엄청 귀찮다


 <TextBlock Text="{Binding Month, StringFormat={}{0}개월}"/>


돈도 

<TextBlock Text="{Binding Money,StringFormat='##,#'}" />


이렇게 하면 300,000 형식으로 나온다.



Posted by 동동(이재동)
wpf2017. 8. 8. 16:18

예를들어 View의 UserControl의 DataContext에 데이터를 주입하고

 <local:CardCancelControl DataContext="{Binding CardCancelData}" />


이런식으로...

유저컨트롤에서 버튼 커맨드를 넣었을때


 <Button Content="확인" Command="{Binding DataContext.CardCancelCommand}"  CommandParameter="Cancel" />


이런식으로 넣으면 안된다. datacontext안에 서 command를 호출하기 때문이다


이렇게 할려면 상위에서 DataContext를 빼야 작동한다.


그러면 상위에서 호출되게 할려면 어떻게 해야할까.


 <Button Content="확인" Command="{Binding Path=DataContext.CardCancelCommand,

                        RelativeSource={RelativeSource Mode=FindAncestor,

                        AncestorType={x:Type local:PopupControl}}}" CommandParameter="Cancel" />


이렇게 하면 된다.

참고 : https://stackoverflow.com/questions/3404707/access-parent-datacontext-from-datatemplate


Posted by 동동(이재동)
wpf2017. 8. 7. 11:29

일반적으로 Grid라든지 컨트롤들은 자동으로 해상도에 맞게 조절해주지만


이미지는 크기가 정해져 있어서 이미지 크기가 유동적으로 변하지 않는다.


그래서 만약 Grid를 사용할때 퍼센트를 이용해서 분할하였다면 이미지를 사용한 Row나 column은 이미지가 짤릴경우가 있다.


이럴때는 ViewBox로 그 Row를 감싸면 깔끔해진다.



Posted by 동동(이재동)
wpf2017. 7. 17. 16:58

Grid 같은 패널에 Add,Clear 하면서 임시로 nagiation처럼 되도록 하는 방법이 있지만


Frame을 이용하면 더 깔끔하게 가능하다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public static class NavigationManager
    {
        private static Frame _mainContentFrame;
 
        public static void SetFrame(Frame frame)
        {
            _mainContentFrame = frame;
        }
 
        public static void Navigate(UserControl page)
        {
            _mainContentFrame.Navigate(page);
        }
    }


Xaml


1
2
3
<Grid x:Name="xMainWindowPanel">
        <Frame x:Name="xMainFrame" NavigationUIVisibility="Hidden" />
</Grid>


사용법


1
2
3
4
5
  private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            NavigationManager.SetFrame(xMainFrame);
            xMainFrame.Navigate(new LoginPage());
        }

추가...

naviagte를 하게 되면 이전 페이지가 필요 있으면 메모리에 남게 되므로 메모리 관리에 문제가 있을수 있다.

 public static void Navigate(UserControl page)
        {
            _mainContentFrame.Navigate(page);

            while (_mainContentFrame.CanGoBack == true)
            {
                _mainContentFrame.RemoveBackEntry();
            }
        }

RemoveBackEntry()로 지워주자


Posted by 동동(이재동)
wpf2016. 6. 8. 15:28
public static class IsolatedStorageManager
{
public static void Save(string text)
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();
StreamWriter srWriter = new StreamWriter(new IsolatedStorageFileStream("path", FileMode.Create, isolatedStorage));
srWriter.WriteLine(text);
srWriter.Flush();
srWriter.Close();
}
public static string Load()
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();
StreamReader srReader = new StreamReader(new IsolatedStorageFileStream("path", FileMode.OpenOrCreate, isolatedStorage));
if (srReader != null)
{
while (!srReader.EndOfStream)
{
string item = srReader.ReadLine();
srReader.Close();
return item;
}
}
srReader.Close();
return @"C:\movie";
}
}


















Posted by 동동(이재동)
wpf2016. 4. 19. 13:24

Bitmap 이미지 프로세싱을 이용하여 흑백, 세피아톤, 반전, 투명, 만화 등의 효과를 사용할 수 있다...


C#에 있는 샘플 코드를  WPF에서 사용할수 있도록 바꾸었다.



필터가 추가 될때마다 소스를 업데이트 하겠다.


참고한 사이트 : https://softwarebydefault.com/2013/03/02/bitmap-image-filters/



ImageFilterTest.zip




조금더 추가한 버전(blur,, 가우시안블러,FuzzEdgeBlur)


ImageFilterTest.zip







'wpf' 카테고리의 다른 글

SoundPlayer 사용  (0) 2016.04.25
blend 디자인모드 무시  (0) 2016.04.21
WPF HtmlToXaml에 Image Add하기  (0) 2016.04.14
image sequence 만들기 (Image Animation)  (0) 2016.04.08
parent usercontrol Owner 상위 찾기  (0) 2016.04.08
Posted by 동동(이재동)
wpf2016. 4. 14. 16:38

대박이다.... 


HtmlToXaml에서 <img src> 태그를 먹이면 적용이 안되었다.


<P> <BR> 등등 기본적인 태그는 테스트 해보니 잘되었다... 왜 이거는 안된것일까


Nuget에서 최신버전을 포함 많은 버전을 다운받아 보았지만 되지를 않았다...


혹시나해서 소스를 까봤더니 대박........ Image 추가하는 메소드에 아무것도 없던것이다.!!!


이놈들이 귀찮거나 문제가 있어서 소스를 지웠거나 아예 구현을 안했을 가능성이 높다...


내가 짜야하나 했는데 구글신을 검색해보니 역시 능력자가 구현해놨다 ㅋㅋ



참조한곳

http://blogs.spencen.com/?p=656


적용해서 해보니 잘되더라~ 


내가 적용해서 솔루션을 만들어 놓음



htmltoxaml.zip






Posted by 동동(이재동)
wpf2016. 4. 4. 11:53


ImageButton.cs


스타일


<Style TargetType="{x:Type c:ImageButton}">

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type c:ImageButton}">

                    <Border x:Name="buttonBorder">

                        <Border.Effect>

                            <DropShadowEffect Opacity="0.0" />

                        </Border.Effect>

                        <Image  Source="{TemplateBinding NormalImage}" x:Name="img" />

                    </Border>

                    <ControlTemplate.Triggers>

                        <Trigger Property="IsPressed" Value="true">

                            <Setter TargetName="img" Property="Source" Value="{Binding PressImage, RelativeSource={RelativeSource TemplatedParent}}" />

                        </Trigger>

                    </ControlTemplate.Triggers>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

    </Style>


사용예 :


<c:ImageButton x:Name="xStartBtn" Width="300" Height="300" Content="Start" NormalImage="/CartoonMuseum;component/Images/sampleBtn.png" PressImage="/CartoonMuseum;component/Images/samplePressBtn.png" />


Themes/Generic.xaml

<Style TargetType="{x:Type c:ImageButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:ImageButton}">
<Border Name="buttonBorder">
<Border.Effect>
<DropShadowEffect Opacity="0.0" />
</Border.Effect>
<Border.Child>
<Image Source="{TemplateBinding NormalImage}" x:Name="img" />
</Border.Child>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="img" Property="Source" Value="{Binding PressImage, RelativeSource={RelativeSource TemplatedParent}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>








ImageButton.cs

public class ImageButton : Button
{
public ImageSource NormalImage
{
get { return base.GetValue(NormalImageProperty) as ImageSource; }
set { base.SetValue(NormalImageProperty, value); }
}
public static readonly DependencyProperty NormalImageProperty =
DependencyProperty.Register("NormalImage", typeof(ImageSource), typeof(ImageButton));
public ImageSource PressImage
{
get { return base.GetValue(PressImageProperty) as ImageSource; }
set { base.SetValue(PressImageProperty, value); }
}
public static readonly DependencyProperty PressImageProperty =
DependencyProperty.Register("PressImage", typeof(ImageSource), typeof(ImageButton));
public ImageButton()
{
DefaultStyleKey = typeof(ImageButton);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
}



Posted by 동동(이재동)
Surface2011. 5. 27. 11:06

WPF에서 이런식으로 스토리를 보여주고 싶었다.(이건 완성된버전 ㅋㅋ)

 

image

 

이건 그냥 TextBlock으로 되는것이 아니다.

 

그래서 FlowDocument를 사용하였다..

 

일단 xaml에서 이렇게 코딩을 했다.

 

<FlowDocumentScrollViewer Grid.Row="1" Grid.ColumnSpan="2" VerticalScrollBarVisibility="Hidden" >
    <FlowDocument Background="Transparent">                                        
        <Paragraph FontFamily="Bell MT" FontSize="24" x:Name="DescriptionParagraph">
            <Floater Width="500"  HorizontalAlignment="Left">                            
                <BlockUIContainer>
                    <Rectangle Height="250" />
                </BlockUIContainer>
            </Floater>
            One Day, most of the town’s roads are ruined by the heavy rain. On that day, school bus-Schoobi happens to be late because of constructions on the road. Worrying that children may be waiting at the bus stop, Schoobi drives through the traffic with full speed, even though other cars are starring at him in a disapproving manner. Schoobi gets to a costal road, however, the road condition there is also messy. Dilly-dallying and regreting to go back. Schoobi ends up ramming into the guardail. Schoobi is now in the danger of falling down the cliff. Can Robocar Poli and his team save Schoobi?
        </Paragraph>
    
    </FlowDocument>
   
</FlowDocumentScrollViewer>
 
보면 알겠지만 FlowDocument에서 Paragraph를 사용하고 안에 Floater를 이용해서 안에 투명한 사각형을 왼쪽에 정렬하고 바깥쪽에 글을 입력하였다.
 
그럼 이제 안에 내용 Text를 계속 유동적으로 바꿔야 한다.
그럼 어떻게 해야할까? behind에서 수정하면 된다.
 
paragrah의 x:name을 DescriptionParagraph를 정의 했으니 이걸 변경하면 된다. 소스를 보자
 
private void SetDescriptionPlaceholder(string param)
        {
            DescriptionParagraph.Inlines.Remove(DescriptionParagraph.Inlines.Where(c => c is System.Windows.Documents.Run == true).Select(c => c).FirstOrDefault());
            DescriptionParagraph.Inlines.Add(param);
        }
 

이렇게 inline을 삭제하고 다시 추가하는 형식으로 바꾸었다.

 

이렇게 하면 끝~

Posted by 동동(이재동)
Surface2011. 5. 19. 16:06

아 이것때문에 시간 아까운데 2시간이나 까먹었다…

 

실버라이트랑 다르게 이상하게

 

Blend로 VisualState를 만들고

 

VisualStateManager.GoToState(this, "Title", true);

 

이렇게 state간의 전환을 할려고 했으나 계속 false를 return 했다. ㅡ.ㅡ!!!

 

인터넷 찾아보니…

 

WPF 버그라던데…

 

해결법은

 

VisualStateManager.GoToElementState(this.Content as FrameworkElement, "Title", true);

 

이렇게 element단위에서 해야한다.. 내참 인터넷에 왜 이런거 해결하는 법 하나도 없는거야?

Posted by 동동(이재동)