'분류 전체보기'에 해당되는 글 744건

  1. 2017.07.17 MVVM Button Click Command 사용법
  2. 2016.10.24 MVVM을 쓰면서... 3
  3. 2016.10.24 바인딩이란?
  4. 2016.10.24 UWP(윈도우 유니버설 응용 프로그램)
  5. 2016.10.04 Huying PC방 버전(2016.8~2016.9)
  6. 2016.09.23 반복적인 xaml name 을 이용할때
  7. 2016.09.08 [WPF] ListBox Selected 되었을때 내용 바꾸기
  8. 2016.08.23 Drag and Drop Cursor (커서) 변경
  9. 2016.08.23 ListBox Drag and Drop
  10. 2016.07.15 app.config 수정 edit
  11. 2016.07.06 Page 기능을 구현할때는 Linq Skip을 활용하자.
  12. 2016.06.20 URI Parameter 붙이기
  13. 2016.06.08 [WPF] IsolatedStorageManager
  14. 2016.05.19 프로그램 죽을때 바로 재시작하게 하기
  15. 2016.05.03 [포트폴리오] POP Camera (2016.04~2016.04) 1주
  16. 2016.05.03 [포트폴리오] Photo AR (2016.4~2016.4) 2주
  17. 2016.04.25 ListBox에서 Item 스크롤 터치시 화면 전체가 움직이던 문제
  18. 2016.04.25 SoundPlayer 사용
  19. 2016.04.21 blend 디자인모드 무시
  20. 2016.04.20 RenderTargetBitmap Memory Leak 해결
  21. 2016.04.20 Simple Uniq ID만들기
  22. 2016.04.19 Image Filter 사용하기 (이미지 프로세싱)
  23. 2016.04.14 WPF HtmlToXaml에 Image Add하기
  24. 2016.04.08 image sequence 만들기 (Image Animation)
  25. 2016.04.08 parent usercontrol Owner 상위 찾기
  26. 2016.04.06 Animation 페이지 넘기기 컨트롤
  27. 2016.04.05 [wpf] Object Capture 컨트롤 캡쳐
  28. 2016.04.04 CustomControl ImageButton
  29. 2016.03.18 [포트폴리오] Windows 10 Store Melon App(2015.10~2016.1)
  30. 2016.01.20 Height를 Width 비율에 맞게 나오게 하는 공식
wpf2017. 7. 17. 16:54

일단 Command를 만든다.

1
2
        private bool _deleteCommand = true;
        public RelayCommand DeleteCommand { get; private set; }
 


ViewModel 생성자에 넣기

1
2
3
4
5
 public MainViewModel()
        {
            DeleteCommand = new RelayCommand(ExcuteDeleteCommand, () => _deleteCommand);
            OrderMenuList = new ObservableCollection<OrderMenu>();
        }



1
2
3
4
 private void ExcuteDeleteCommand()
        {
            OrderMenuList.RemoveAt(OrderMenuList.Count - 1);
        }


xaml코드에는


1
<Button x:Name="xdelete" Content="삭제"  Height="50" Margin="20" Command="{Binding DeleteCommand}" />


여러가지 파라미터를 사용하고 싶으면 여기 참고

https://msdn.microsoft.com/en-us/magazine/dn237302.aspx

'wpf' 카테고리의 다른 글

listbox에서 오른쪽 정렬하고 싶을때  (0) 2017.07.18
[WPF] NavagionManager  (0) 2017.07.17
MVVM을 쓰면서...  (3) 2016.10.24
바인딩이란?  (0) 2016.10.24
반복적인 xaml name 을 이용할때  (0) 2016.09.23
Posted by 동동(이재동)
wpf2016. 10. 24. 15:37

6년동안 MVVM을 쓰면서.. 느낀점을 알아보자..


일단 MVVM이란


Model : 보통 Data를 담는 그릇정도로 생각

View :  디스플레이 사용자가 보여지는것, UI, 디자이너의 영역이라고 정의해두자.

ViewMode: View의 표현을 담당한다고 보면 된다. 보통 View에 Data를 표현해준다.  

보통 ViewModel이 변경되면 View에 자동으로 업데이트 하는 방식으로 구현된다.


MVVM을 사용했을때 장점은 머가 있었을까...

-일단 View와 비지니스 로직의 연결이다. 뷰나 비지니스 로직 둘중에 하나가 변경 되더라도 다른 부분에 영향을 미치지 않는다. 따라서 디자이너와의 협업 시스템이 정말 용의 하다. 실제로 디자이너랑 엄청 편리하게 작업을 해왔다.


-ICommand의 각종 이벤트나 익터렉션 처리를 ICommand를 호출해서 사용하는데 간단하게 이야기 하면

이벤트를 뷰모델과 연결하는 방법이다. 근데 은근히 귀찮고 짜증나서 사용하기가 싫다. 그냥 BeHind로 하고 싶다!!!!!


-Binding 사용가능

등등


장점만 있는거 같지만 단점도 많다..


가장 중요한 귀찮다!! 귀찮다!! 귀찮다!

페이지 하나 만들려고 해도 VIewModel을 따로 만들어야 하니 귀찮니즘땜에 죽겠다.

그리고 이벤트 연결 그냥 비하인드에 해도 되는데 ICommmand 쓰면 코드가 몇줄이나 늘어난다.

그리고 디버깅도 더 힘들다.

그리고 View처리가 복잡해지면 ViewModel Class가 엄청나게 커진다.


이렇게 장단점이 있기때문에 상황에 맞게 잘사용해야할꺼 같다..

무조건 MVVM을 고집하는건 좀 아닌거 같다는 생각이 든다.












'wpf' 카테고리의 다른 글

[WPF] NavagionManager  (0) 2017.07.17
MVVM Button Click Command 사용법  (0) 2017.07.17
바인딩이란?  (0) 2016.10.24
반복적인 xaml name 을 이용할때  (0) 2016.09.23
[WPF] ListBox Selected 되었을때 내용 바꾸기  (0) 2016.09.08
Posted by 동동(이재동)
wpf2016. 10. 24. 15:23

WPF 기준으로 바인딩이란

XAML로 표현되는 UI 요소와 ViewModel로 표현되는 데이터 사이에 관계를 맺는 기술을 의미한다.


이를 통해서 UI부분과 데이터 부분을 서로 독립적으로 다를수 있으며 이것은 곧 UI디자이너와 개발자의 역활을 보다 분명하게 정의하고 협업에 효율적으로 할수 있게한다.

'wpf' 카테고리의 다른 글

MVVM Button Click Command 사용법  (0) 2017.07.17
MVVM을 쓰면서...  (3) 2016.10.24
반복적인 xaml name 을 이용할때  (0) 2016.09.23
[WPF] ListBox Selected 되었을때 내용 바꾸기  (0) 2016.09.08
Drag and Drop Cursor (커서) 변경  (0) 2016.08.23
Posted by 동동(이재동)
Windows10 App2016. 10. 24. 15:20

8에서 10으로 바뀌면서 가장 크게 바뀐게 유니버설로 바뀐것이다.

이제, 윈도우 10, 유니버설 응용 프로그램 플랫폼의 이름은 범용 윈도우 플랫폼 (UWP)로 변경되었다. PC, 태블릿, 휴대 전화,로 Windows 스토어의 Windows 10 장치를 대상으로 현대 완전히 몰입 애플리케이션을 구축 할 수 있다.


개발은 HTML과 C# With Xaml로 개발 가능하다.


개발하기 위해서 필요한것

-비쥬얼 스튜디오

-개발자 모드 On

-앱개발자 등록


'Windows10 App' 카테고리의 다른 글

윈도우즈 스토어 앱에서 윈도우 버전 알기  (0) 2015.07.03
Posted by 동동(이재동)
포트폴리오2016. 10. 4. 16:42

중국에서 사용되고 있는 Huying PC방 버전


-PC방에서 이용중인 사용자들을 볼수 있고 비슷한 게임을 즐기는 사람과 게임 정보 공유및 친구를 사귈수 있음

-핸드폰으로 WECHAT 정보를 입력하면 자동으로 프로그램에 QR코드와 정보가 업데이트 됨

-광고로 수입 낼수 있음

-게임방 음식 메뉴를 고를수 있으며 앱을 이용하여 쉽게 결제 가능



Posted by 동동(이재동)
wpf2016. 9. 23. 10:47

예를 들면 xaml에서


<border x:name="border1" />

<border x:name="border2" />


이렇게 있다고 하면 behind에서 힘들게 이름을 찾지 말고


var temp = (Border)this.FindName("border1");


요렇게 하면 된다.


'wpf' 카테고리의 다른 글

MVVM을 쓰면서...  (3) 2016.10.24
바인딩이란?  (0) 2016.10.24
[WPF] ListBox Selected 되었을때 내용 바꾸기  (0) 2016.09.08
Drag and Drop Cursor (커서) 변경  (0) 2016.08.23
ListBox Drag and Drop  (0) 2016.08.23
Posted by 동동(이재동)
wpf2016. 9. 8. 18:04
<s:SurfaceListBox x:Name="xListbox" >
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel>
<TextBlock Text="1057-1966" x:Name="xYearTextBlock" />
<TextBlock Text="약국에서 시작될꿈 제약으로 " />
</StackPanel>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Value="True" Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}">
<Setter TargetName="xYearTextBlock" Property="Text" Value="HotPink" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
</s:SurfaceListBox>



<DataTrigger Value="True" Binding="{Binding IsSelected, ElementName=xListbox}">

이런식으로 elementname으로도 가능하다

DateTemplte 안에 Triggers를 이용하면 아주 간단하게 된다. 이예제는 DataTemple에 있는 xYearTextBlock Text를 바꾼것이다.

간단한 배경이나 글자 컬러정도는 컨테이너 스타일로도 바꿀수 있다.

<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Red" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>


'wpf' 카테고리의 다른 글

바인딩이란?  (0) 2016.10.24
반복적인 xaml name 을 이용할때  (0) 2016.09.23
Drag and Drop Cursor (커서) 변경  (0) 2016.08.23
ListBox Drag and Drop  (0) 2016.08.23
app.config 수정 edit  (0) 2016.07.15
Posted by 동동(이재동)
wpf2016. 8. 23. 17:22

-일반적인 cur 파일로 변경방법


private void Label_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataObject data = new DataObject(DataFormats.Text, ((Label)e.Source).Content);
DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
}
private void Label_Drop(object sender, DragEventArgs e)
{
((Label)e.Source).Content = (string)e.Data.GetData(DataFormats.Text);
}
private Cursor customCursor = null;
private void Label_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effects == DragDropEffects.Copy)
{
if (customCursor == null)
customCursor = new Cursor(new FileStream("Earth.cur", FileMode.Open));
e.UseDefaultCursors = false;
Mouse.SetCursor(customCursor);
}
else
e.UseDefaultCursors = true;
e.Handled = true;
}

-UserControl(UI Element)로 바꾸는 방법

namespace VISION.IdeaParkinglot.Managers
{
public class CursorManager
{
private static class NativeMethods
{
public struct IconInfo
{
public bool fIcon;
public int xHotspot;
public int yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
[DllImport("user32.dll")]
public static extern SafeIconHandle CreateIconIndirect(ref IconInfo icon);
[DllImport("user32.dll")]
public static extern bool DestroyIcon(IntPtr hIcon);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
}
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
private class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeIconHandle()
: base(true)
{
}
override protected bool ReleaseHandle()
{
return NativeMethods.DestroyIcon(handle);
}
}
private static Cursor InternalCreateCursor(System.Drawing.Bitmap bmp)
{
var iconInfo = new NativeMethods.IconInfo();
NativeMethods.GetIconInfo(bmp.GetHicon(), ref iconInfo);
iconInfo.xHotspot = 0;
iconInfo.yHotspot = 0;
iconInfo.fIcon = false;
SafeIconHandle cursorHandle = NativeMethods.CreateIconIndirect(ref iconInfo);
return CursorInteropHelper.Create(cursorHandle);
}
public static Cursor CreateCursor(UIElement element)
{
element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
element.Arrange(new Rect(new Point(), element.DesiredSize));
RenderTargetBitmap rtb =
new RenderTargetBitmap(
(int)element.DesiredSize.Width,
(int)element.DesiredSize.Height,
96, 96, PixelFormats.Pbgra32);
rtb.Render(element);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
using (var ms = new MemoryStream())
{
encoder.Save(ms);
using (var bmp = new System.Drawing.Bitmap(ms))
{
return InternalCreateCursor(bmp);
}
}
}
}
}

요기는 giveFeedBack에 쓸것
private void Label_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effects == DragDropEffects.Copy)
{
if (customCursor == null)
customCursor = CursorHelper.CreateCursor(e.Source as UIElement);
if (customCursor != null)
{
e.UseDefaultCursors = false;
Mouse.SetCursor(customCursor);
}
}
else
e.UseDefaultCursors = true;
e.Handled = true;
}





참고 : https://wpf.2000things.com/2012/12/17/713-setting-the-cursor-to-an-image-of-an-uielement-while-dragging/









'wpf' 카테고리의 다른 글

반복적인 xaml name 을 이용할때  (0) 2016.09.23
[WPF] ListBox Selected 되었을때 내용 바꾸기  (0) 2016.09.08
ListBox Drag and Drop  (0) 2016.08.23
app.config 수정 edit  (0) 2016.07.15
[WPF] IsolatedStorageManager  (0) 2016.06.08
Posted by 동동(이재동)
wpf2016. 8. 23. 15:41

일단 참고


http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/



Posted by 동동(이재동)
wpf2016. 7. 15. 12:44
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}



Posted by 동동(이재동)
c#2016. 7. 6. 13:41

Linq가 없는 시절  페이징 할려면 


private List<Data> MakePhotoList(int startCount)
{
var tempPhotoList = new List<Data>();
int maxCount = startCount + 9;
for (int i = startCount; startCount < maxCount; startCount++)
{
tempPhotoList.Add(_photoList[i]);
}
return tempPhotoList;
}


이런식으로 해야만 했다.

하지만 Linq가 있으면

_photoList.Skip(startCount).Take(9).ToList();

한줄로 끝~


'c#' 카테고리의 다른 글

사용하지 않을 메소드앞에 [Obsolete] 어트리뷰트 사용  (0) 2020.01.03
list 삭제  (0) 2019.08.02
URI Parameter 붙이기  (0) 2016.06.20
RenderTargetBitmap Memory Leak 해결  (0) 2016.04.20
Simple Uniq ID만들기  (0) 2016.04.20
Posted by 동동(이재동)
c#2016. 6. 20. 13:45
public static Uri AttachParameters(this Uri uri, NameValueCollection parameters)
{
var stringBuilder = new StringBuilder();
string str = "?";
for (int index = 0; index < parameters.Count; ++index)
{
stringBuilder.Append(str + parameters.AllKeys[index] + "=" + parameters[index]);
str = "&";
}
return new Uri(uri + stringBuilder.ToString());
}





var uri = new Uri(BaseUrl + "/TableQRCodeUpdate").AttachParameters(new NameValueCollection
{
{"TableKey",tableKey},
{"TableQRCode",tableQrCode}
});

이렇게 사용하면 된다.


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. 5. 19. 14:46

전시회에서 프로그램이 죽어서 꺼지게 되면 난감하다.


그걸 방지하기 위한 꼼수로 프로그램을 잘짜면 죽지는 않겠지만


간혹가다 생기는 메모리 누수및 관리로 인해 프로그램이 죽을때도 있기에 안정장치로 설정할 수 있다.


app.xaml.cs 에서


this.DispatcherUnhandledException += App_DispatcherUnhandledException;


 private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)

        {

            Thread.Sleep(1000);

            System.Windows.Forms.Application.Restart();

            Thread.Sleep(1000);

            Process.GetCurrentProcess().Kill();

        }


컴퓨터가 빠를경우 sleep을 사용할필요가 없는데 느린경우가 있어서 썼다.

'wpf' 카테고리의 다른 글

app.config 수정 edit  (0) 2016.07.15
[WPF] IsolatedStorageManager  (0) 2016.06.08
ListBox에서 Item 스크롤 터치시 화면 전체가 움직이던 문제  (0) 2016.04.25
SoundPlayer 사용  (0) 2016.04.25
blend 디자인모드 무시  (0) 2016.04.21
Posted by 동동(이재동)
포트폴리오2016. 5. 3. 14:27

Photo AR을 만들고 난 뒤 라이브러리를 이용해서 레이아웃및 디자인 , 몇가지 기능 추가 및 삭제 해서 만든 프로그램


이미 Photo AR에서 여러가지 시행착오를 거쳤기에 재활용해서 금방 만들 수 있었다.











Posted by 동동(이재동)
포트폴리오2016. 5. 3. 14:25

영화관이나 행사장 근처에서 사진찍으면 이메일로 보내주는 딱 그런 용도이다...


키오스크에 들어가는 프로그램으로


사용자가 캠으로 사진을 찍고 배경, 필터, 스티커 등을 마음대로 편집할 수 있는


프로그램 서버로부터 이미지 및 데이터를 미리 다운로드 하는 방식으로 유연하다


카메라 메모리 관리하는부분이 개인적으로 힘들었던 프로젝트였다.
















Posted by 동동(이재동)
wpf2016. 4. 25. 13:36

이상하게 ListBox에서 Item끝으로 터치하면 프로젝트 화면 전체가 움직였다.


여러가지 실험을 해본 결과 


xMakeupListPanel.ManipulationBoundaryFeedback += XMakeupListPanel_ManipulationBoundaryFeedback;
private void XMakeupListPanel_ManipulationBoundaryFeedback(object sender, ManipulationBoundaryFeedbackEventArgs e)
{
e.Handled = true;
}

이렇게 해결 하였다..

참고 : http://stackoverflow.com/questions/4505772/wpf-listbox-with-touch-inertia-pulls-down-entire-window


'wpf' 카테고리의 다른 글

[WPF] IsolatedStorageManager  (0) 2016.06.08
프로그램 죽을때 바로 재시작하게 하기  (0) 2016.05.19
SoundPlayer 사용  (0) 2016.04.25
blend 디자인모드 무시  (0) 2016.04.21
Image Filter 사용하기 (이미지 프로세싱)  (0) 2016.04.19
Posted by 동동(이재동)
wpf2016. 4. 25. 11:26

사운드 파일  실행


SoundPlayer sp = new SoundPlayer(Resources.Click);
sp.Play();


해당 프로젝트 Resources.resx에서 상단에 리소스 추가 버튼을 누른후 wav파일을 등록후 사용한다~


Posted by 동동(이재동)
wpf2016. 4. 21. 17:47

DesignerProperties.GetIsInDesignMode(this)



출처 : http://www.stievens-corner.be/index.php/10-wpf/47-designerproperties-getisindesignmode

Posted by 동동(이재동)
c#2016. 4. 20. 14:43


       bmp.Freeze();  
       bmp = null;  
       GC.Collect();  
       GC.WaitForPendingFinalizers();  
       GC.Collect(); 


bmp는 rendertargetbitmap


가비지컬렉터를 수동으로 호출 해야한다.;;



출처 : http://stackoverflow.com/questions/29560264/rendertargetbitmap-impossible-to-free-dispose-handle

'c#' 카테고리의 다른 글

사용하지 않을 메소드앞에 [Obsolete] 어트리뷰트 사용  (0) 2020.01.03
list 삭제  (0) 2019.08.02
Page 기능을 구현할때는 Linq Skip을 활용하자.  (0) 2016.07.06
URI Parameter 붙이기  (0) 2016.06.20
Simple Uniq ID만들기  (0) 2016.04.20
Posted by 동동(이재동)
c#2016. 4. 20. 11:05
Guid.NewGuid()

출처 : http://stackoverflow.com/questions/11313205/generate-a-unique-id

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. 8. 16:54

이미지 여러장을 이용해서 애니메이션을 만드는것


ImageSequence.zip


참고 : http://coderelief.net/2009/05/21/frame-based-animation-in-wpf/


public partial class MainWindow : Window
{
public static readonly DependencyProperty FramesPerSecondProperty = DependencyProperty
.Register("FramesPerSecond", typeof(double), typeof(MainWindow));
private List<string> imageList = new List<string>();
private TimeSpan LastRenderTime { get; set; }
public double FramesPerSecond
{
get { return (double)GetValue(FramesPerSecondProperty); }
set
{
if (value <= 0)
{
throw new Exception("FramesPerSecond must be greater than 0.");
}
SetValue(FramesPerSecondProperty, value);
}
}
private int index = 1;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 21; i++)
{
imageList.Add(string.Format("/ImageSequence;component/Images/e2000{0}.png", i));
}
FramesPerSecond = 10;
CompositionTarget.Rendering += CompositionTarget_Rendering;
}
private void CompositionTarget_Rendering(object sender, EventArgs e)
{
TimeSpan timeSinceLastRender;
timeSinceLastRender = (DateTime.Now.TimeOfDay - LastRenderTime);
if (timeSinceLastRender.TotalSeconds < (1 / FramesPerSecond))
{
return;
}
LastRenderTime = DateTime.Now.TimeOfDay;
if (index < 20)
{
xImage.Source = new BitmapImage(new Uri(imageList[index], UriKind.RelativeOrAbsolute));
index++;
}
else
{
index = 1;
}
}
}


Posted by 동동(이재동)
wpf2016. 4. 8. 14:24

DependencyObject ucParent = _parent.Parent;
while (!(ucParent is UserControl))
{
ucParent = LogicalTreeHelper.GetParent(ucParent);
}


하위 UserControl에서 상위 UserControl의 Owner 찾는법

참조 : http://stackoverflow.com/questions/1474438/wpf-get-usercontrol-owner


'wpf' 카테고리의 다른 글

WPF HtmlToXaml에 Image Add하기  (0) 2016.04.14
image sequence 만들기 (Image Animation)  (0) 2016.04.08
Animation 페이지 넘기기 컨트롤  (0) 2016.04.06
[wpf] Object Capture 컨트롤 캡쳐  (0) 2016.04.05
CustomControl ImageButton  (0) 2016.04.04
Posted by 동동(이재동)
wpf2016. 4. 6. 13:47
페이지가 여러개 있을때 페이지 넘기는 효과를 준다. 여러가지 type이 있다.

ContentTemplateSelector가 변경되었을때 이벤트를 이용하기때문에 TempleteSelector를 만들어야 한다.


샘플 파일


사용법 Xaml

<local:AnimatedContentControl AnimationDuration="0:0:1.0" Content="{Binding NavigationState}" AnimateType="Right" Height="200" ContentTemplateSelector="{DynamicResource MainTemplateSelector}">
</local:AnimatedContentControl>

TemplateSelector.cs

public class MainTemplateSelector : DataTemplateSelector
{
public DataTemplate TestTemplate { get; set; }
public DataTemplate LoadingTemplate { get; set; }
public MainTemplateSelector()
{
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if ((item as string) == "Loading")
{
return LoadingTemplate;
}
else
{
return TestTemplate;
}
return base.SelectTemplate(item, container);
}
}


AnimationContentControl.cs
public enum AnimateType
{
Right,
Top,
Down,
Left,
Opacity,
}
/// <summary>
/// A ContentControl that animates the transition between content
/// </summary>
[TemplatePart(Name = "PART_PaintArea", Type = typeof(Shape)),
TemplatePart(Name = "PART_MainContent", Type = typeof(ContentPresenter))]
public class AnimatedContentControl : ContentControl
{
public AnimateType AnimateType
{
get { return (AnimateType)GetValue(AnimateTypeProperty); }
set { SetValue(AnimateTypeProperty, value); }
}
// Using a DependencyProperty as the backing store for AnimateType. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AnimateTypeProperty =
DependencyProperty.Register("AnimateType", typeof(AnimateType), typeof(AnimatedContentControl), new PropertyMetadata(AnimateType.Left));
#region Generated static constructor
static AnimatedContentControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedContentControl), new FrameworkPropertyMetadata(typeof(AnimatedContentControl)));
}
#endregion Generated static constructor
public TimeSpan AnimationDuration
{
get { return (TimeSpan)GetValue(AnimationDurationProperty); }
set { SetValue(AnimationDurationProperty, value); }
}
// Using a DependencyProperty as the backing store for AnimationDuration. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AnimationDurationProperty =
DependencyProperty.Register("AnimationDuration", typeof(TimeSpan), typeof(AnimatedContentControl), new PropertyMetadata(TimeSpan.FromSeconds(0.5)));
public IEasingFunction EasingFunction
{
get { return (IEasingFunction)GetValue(EasingFunctionProperty); }
set { SetValue(EasingFunctionProperty, value); }
}
// Using a DependencyProperty as the backing store for EasingFunction. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register("EasingFunction", typeof(IEasingFunction), typeof(AnimatedContentControl), new PropertyMetadata(new PowerEase() { EasingMode = EasingMode.EaseInOut }));
private Shape m_paintArea;
private ContentPresenter m_mainContent;
/// <summary>
/// This gets called when the template has been applied and we have our visual tree
/// </summary>
public override void OnApplyTemplate()
{
m_paintArea = Template.FindName("PART_PaintArea", this) as Shape;
m_mainContent = Template.FindName("PART_MainContent", this) as ContentPresenter;
base.OnApplyTemplate();
}
protected override void OnContentTemplateSelectorChanged(DataTemplateSelector oldContentTemplateSelector, DataTemplateSelector newContentTemplateSelector)
{
base.OnContentTemplateSelectorChanged(oldContentTemplateSelector, newContentTemplateSelector);
if (ContentTemplateSelector != null)
{
ContentTemplate = ContentTemplateSelector.SelectTemplate(Content, null);
}
}
protected override void OnContentTemplateChanged(DataTemplate oldContentTemplate, DataTemplate newContentTemplate)
{
base.OnContentTemplateChanged(oldContentTemplate, newContentTemplate);
}
/// <summary>
/// This gets called when the content we're displaying has changed
/// </summary>
/// <param name="oldContent">The content that was previously displayed</param>
/// <param name="newContent">The new content that is displayed</param>
protected override void OnContentChanged(object oldContent, object newContent)
{
if (m_paintArea != null && m_mainContent != null)
{
m_paintArea.Fill = CreateBrushFromVisual(m_mainContent);
BeginAnimateContentReplacement();
}
if (ContentTemplateSelector != null)
{
ContentTemplate = ContentTemplateSelector.SelectTemplate(newContent, null);
}
base.OnContentChanged(oldContent, newContent);
}
/// <summary>
/// Starts the animation for the new content
/// </summary>
private void BeginAnimateContentReplacement()
{
var newContentTransform = new TranslateTransform();
var oldContentTransform = new TranslateTransform();
m_paintArea.RenderTransform = oldContentTransform;
m_mainContent.RenderTransform = newContentTransform;
m_paintArea.Visibility = Visibility.Visible;
switch (AnimateType)
{
case AnimateType.Top:
newContentTransform.BeginAnimation(TranslateTransform.YProperty, CreateAnimation(-this.ActualHeight, 0));
oldContentTransform.BeginAnimation(TranslateTransform.YProperty, CreateAnimation(0, this.ActualHeight, (s, e) => m_paintArea.Visibility = Visibility.Hidden));
break;
case AnimateType.Down:
newContentTransform.BeginAnimation(TranslateTransform.YProperty, CreateAnimation(this.ActualHeight, 0));
oldContentTransform.BeginAnimation(TranslateTransform.YProperty, CreateAnimation(0, -this.ActualHeight, (s, e) => m_paintArea.Visibility = Visibility.Hidden));
break;
case AnimateType.Left:
newContentTransform.BeginAnimation(TranslateTransform.XProperty, CreateAnimation(-this.ActualWidth, 0));
oldContentTransform.BeginAnimation(TranslateTransform.XProperty, CreateAnimation(0, this.ActualWidth, (s, e) => m_paintArea.Visibility = Visibility.Hidden));
break;
case AnimateType.Right:
newContentTransform.BeginAnimation(TranslateTransform.XProperty, CreateAnimation(this.ActualWidth, 0));
oldContentTransform.BeginAnimation(TranslateTransform.XProperty, CreateAnimation(0, -this.ActualWidth, (s, e) => m_paintArea.Visibility = Visibility.Hidden));
break;
case AnimateType.Opacity:
m_mainContent.BeginAnimation(UIElement.OpacityProperty, CreateAnimation(0, 1));
m_paintArea.BeginAnimation(UIElement.OpacityProperty, CreateAnimation(1, 0, (s, e) => m_paintArea.Visibility = Visibility.Hidden));
break;
default:
break;
}
}
/// <summary>
/// Creates the animation that moves content in or out of view.
/// </summary>
/// <param name="from">The starting value of the animation.</param>
/// <param name="to">The end value of the animation.</param>
/// <param name="whenDone">(optional) A callback that will be called when the animation has completed.</param>
private AnimationTimeline CreateAnimation(double from, double to, EventHandler whenDone = null)
{
var anim = new DoubleAnimation(from, to, AnimationDuration) { EasingFunction = EasingFunction };
if (whenDone != null)
anim.Completed += whenDone;
anim.Freeze();
return anim;
}
/// <summary>
/// Creates a brush based on the current appearnace of a visual element. The brush is an ImageBrush and once created, won't update its look
/// </summary>
/// <param name="v">The visual element to take a snapshot of</param>
private Brush CreateBrushFromVisual(Visual v)
{
if (v == null)
throw new ArgumentNullException("v");
var target = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32);
target.Render(v);
var brush = new ImageBrush(target) { AlignmentY = AlignmentY.Top, Stretch = Stretch.None };
brush.Freeze();
return brush;
}
}


Posted by 동동(이재동)
wpf2016. 4. 5. 18:16
Usercontrol등 Element등을 캡쳐 할수 있도록 만들었다.

용도는 캠 이미지위에 배경및 각종 clip art들을 얹혀서 캡쳐 하기위한 용도~


public static string SaveCamCapture(string filePath, FrameworkElement targetControl)
{
targetControl.UpdateLayout();
// Get the size of the Visual and its descendants.
Rect rect = VisualTreeHelper.GetDescendantBounds(targetControl);
// Make a DrawingVisual to make a screen
// representation of the control.
DrawingVisual dv = new DrawingVisual();
// Fill a rectangle the same size as the control
// with a brush containing images of the control.
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush brush = new VisualBrush(targetControl);
ctx.DrawRectangle(brush, null, new Rect(rect.Size));
}
RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)(targetControl.ActualWidth), (int)(targetControl.ActualHeight), 96, 96, PixelFormats.Pbgra32);
targetBitmap.Render(dv);
var bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
if (filePath != null)
{
using (var filestream = new FileStream(filePath, FileMode.Create))
{
bitmapEncoder.Save(filestream);
}
}
return filePath;
}





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 동동(이재동)
포트폴리오2016. 3. 18. 12:58

기존 윈도우 8, 8.1에서만 동작하던 멜론 앱을 10에서도 잘 작동하도록 수정하였다.


수정과정에서 기획변경 및 멜론 DJ 멜군 업그레이드 및 새로운 기능 설정창 추가 등등 여러가지를 업그레이드 하였다.


서버쪽 이슈등도 모두 대응 









Posted by 동동(이재동)
wpf2016. 1. 20. 16:10

PC에서는 잘나오지만 태블릿 해상도에서는 짤려서 나와서

처방을 한 코드


loaded 이벤트
root.Width = 1920;
root.Height = this.ActualHeight / this.ActualWidth * 1920;
xaml 디자인
<Viewbox> <Grid x:Name="root">


'wpf' 카테고리의 다른 글

[wpf] Object Capture 컨트롤 캡쳐  (0) 2016.04.05
CustomControl ImageButton  (0) 2016.04.04
웹캠위에 이미지를 오버랩 하여 스크린샷 찍기  (0) 2015.12.08
[wpf] 핑테스트 가능 코드  (0) 2009.09.29
[wpf] about Thread Pool  (1) 2009.09.24
Posted by 동동(이재동)