SlideShare uma empresa Scribd logo
강남 DataBinding 스타일
Windows 8 앱개발자라면 꼭 알아야할



개발자가 알아야할 Binding
Non-DataBinding vs. DataBinding
 <Grid>                                 <Grid>
   <TextBlock x:Name=“TitleText”/>        <TextBlock Text=“{Binding Title}”/>
   <TextBlock x:Name=“SubTitleText”/>     <TextBlock Text=“{Binding SubTitle}”/>
 </Grid>                                </Grid>




 TitleText.Text = item.Title;           this.DataContext = item;
 SubTitleText.Text = item.SubTitle;
버튼 누가 지웠어!
Non-DataBinding vs. DataBinding
 <Grid>                               <Grid>
   <HyperlinkButton />                  <HyperlinkButton Content=“{Binding Title}”/>


 </Grid>                              </Grid>




 TitleText.Text = item.Title;         this.DataContext = item;
 SubTitleText.Text = item.SubTitle;



 컴파일 에러 발생!!!                         컴파일 에러 없음
                                      UI와 코드의 분리
                                      개발자와 디자이너 업무영역의 분리
                                      PEACE!
이번 앨범 타이틀 곡이 뭐야?
문맥
문맥
문맥 = Context
DataContext
FrameworkElement.DataContext
  거의 모든 UI는 FrameworkElement
가정

class Chart

+ Album FirstAlbum
                       class Album
+ List<Album> Albums

                       + string CoverArt
                       + string Name
                       + Artist Artist     class Artist

                                           + string ProfilerImage
                                           + string Name
자식에게 상속하는 DataContext
Visual Tree

 Grid(LayoutRoot)        <Grid x:Name=“LayoutRoot”
      Image
                               DataContext=“{Binding TopAlbum}”>
                           <Image Source=“{Binding CoverArt}”/>
      TextBlock
                           <TextBlock Text=“{Binding Title}”/>
      Grid                 <StackPanel DataContext=“{Binding Artist}”>
             Image             <Image Source=“{Binding ProfileImage}”/>
             TextBlock
                               <TextBlock Text=“{Binding Name}”/>
                           </StackPanel>
                         </Grid>
자식에게 상속하는 DataContext
Visual Tree

 Grid(LayoutRoot)        <Grid x:Name=“LayoutRoot”
      Image
                               DataContext=“{Binding TopAlbum}”>
                           <Image Source=“{Binding CoverArt}”/>
      TextBlock
                           <TextBlock Text=“{Binding Title}”/>
      Grid                 <StackPanel>
             Image             <Image Source=“{Binding Artist.ProfileImage}”/>
             TextBlock
                               <TextBlock Text=“{Binding Artist.Name}”/>
                           </StackPanel>
                         </Grid>
DataContext 주입법
In C#

var chart = GetKPopChart();
this.DataContext = chart;




In XAML

<Page>                                          <Page>
  <Page.Resources>                                <Page.DataContext>
    <models:KPopChart x:Key=“Chart” />              <models:KPopChart x:Key=“Chart” />
  </Page.Resources>                               </Page.DataContext>
  <Grid DataContext=“{StaticResource Chart}”>     <Grid >
  …..                                             …..
  </Grid>                                         </Grid>
</Page>                                         </Page>
Binding
문법
•   Binding
     –   Text="{Binding Title}"
•   Path (생략가능)
     –   Text=“{Binding Path=Title}”
•   Source
     –   Text=“{Binding Name, Source={StaticResource MyViewModel}}”
•   Converter
     –   Text=“{Binding PublishDate, Converter={StaticResource FamiliarDateString}}”
•   ConverterParameter
     –   Text=“{Binding Price, Converter={StaticResource CurrencyConverter},
         ConverterParameter={0:C2}}”
{Binding }
•   DataContext 자기 자신!

    <TextBlock Text=“{Binding }” />
ItemsControl
ItemsControl 가족
•   ListView                    Control
•   GridView
•   FlipView
•   ListBox                   ItemsControl   .ItemsSource 프로퍼티가 여기 정의

•   ComboBox

                                Selector




               ListViewBase                   FlipView       ListBox    ComboBox




         ListView        GridView
ItemsControl에서 DataContext 분배
 CS에서
var artists = new List<Artist>()
{                                              싸이
  new Artist() { Name = “싸이”, CoverArt=“…”},
  new Artist() { Name = “아이
유”, CoverArt=“…”},                             아이유
  new Artist() { Name = “싸이”, CoverArt=“…”},
  new Artist() { Name = “아이
유”, CoverArt=“…”},
}                                              싸이

this.Artists = artist;
….
 XAML에서
                                               아이유


<ListView ItemsSource=“{Binding Artists}” />
ItemTemplate과 DataContext
new Artist()
{                                           싸이
  Name = “싸이”,
  CoverArt=“…”,
}                               <ListView.ItemTemplate>
                                   <DataTemplate>
ItemsSource의 인스턴스 하나가                <Grid>
ListViewItem 하나의 DataContext가           <StackPanel>
된다.                                       <Image Source=“{Binding CoverArt}”
                                />
                                          <TextBlock Text=“{Binding Name}” />
                                        </StackPanel>
                                     </Grid>
                                   </DataTemplate>
                                </ListView.ItemTemplate>
In the hood
    ItemsControl의 virtual PrepareContainerForItemOverride(…) 에서


protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
        var contentControl = element as ContentControl;

        contentControl.ContentTemplate = this.ItemTemplate;
        contentControl.DataContext = item;
}
INotifyPropertyChanged
INotifyCollectionChanged
약속
컨트롤은 INotifyPropertyChanged.PropertyChanged를 구독합니다.
컨트롤은 INotifyCollectionChanged.CollectionChanged를 구독합니다.




Common/BindableBase.cs 에서
public abstract class BindableBase : INotifyPropertyChanged



System.Collections.ObjectModel

public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged
이미 구현되어 있는 것
    DataModel/SampleDataSource.cs에서

public abstract class SampleDataCommon : App4.Common.BindableBase


    프로퍼티 예 : Title
private string _title = string.Empty;
public string Title
{
   get { return this._title; }
   set { this.SetProperty(ref this._title, value); }
}

    In the Hood
protected bool SetProperty<T>(ref T storage, T value,
               [CallerMemberName] String propertyName = null)
{
  if (object.Equals(storage, value)) return false;

     storage = value;
     this.OnPropertyChanged(propertyName);
     return true;
}
List<Artist> vs. ObservableCollection<Artist>

this.Artist.Add(new Artist());   this.Artist.Add(new Artist());



           싸이                                싸이


           아이유                               아이유



           싸이                                싸이



                                             아이유
Converter
어떤 필요, 어떤 니즈?
public List<string> Artists { get; set; }

…

Artists = new List<string>()
{
   “싸이”,
   “아이유”,
};

                                            너랑 나랑 강남스타일
                                            싸이, 아이유
샘플 ArtistConverter
namespace MyApp
{
  public class ArtistConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, string language)
    {
       // null 체크, value가 Ienumerable 타입이 아닐 때 예외처리 (생략)

            var list = value as IEnumerable;
            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
               if (sb.Length > 0)
                   sb.Append(“, “);

                sb.Append((string)item);
            }

            return sb.ToString();
        }
    }
}
사용법
인스턴스 생성 (어딘가에) -> 바인딩 식에서 잘 사용
In MyView.xaml (or App.xaml)
<Page>
   <Page.Resources>
     <conv:ArtistConverter x:Key=“ArtistConverter”/>
   </Page.Resources>
   <Grid x:Name=“LayoutRoot”>
     …
     <TextBlock Text=“{Binding Artists,
                                                           너랑 나랑 강남스타일
           Converter={StaticResource ArtistConverter}”/>   싸이, 아이유
   </Grid>
</Page>
Blend 도와줘!
Sample Project
 Code Review
GridApp 샘플 프로젝트에서
GroupedItemsPage.xaml.cs에서

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
  // TODO: Create an appropriate data model for your problem domain to replace the sample data
  var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
  this.DefaultViewModel["Groups"] = sampleDataGroups;
}


GroupedItemsPage.xaml에서
<common:LayoutAwarePage
  x:Name="pageRoot"
  x:Class="App4.GroupedItemsPage"
  DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}“

…
    <CollectionViewSource
       x:Name="groupedItemsViewSource"
       Source="{Binding Groups}"
FIN
즐거운 해커쏜(θ) 되세요!

Mais conteúdo relacionado

Mais procurados

Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Eelco Visser
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Reflection with xamarin.forms
Reflection with xamarin.formsReflection with xamarin.forms
Reflection with xamarin.forms道化師 堂華
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDBJames Williams
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDBScott Hernandez
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Tobias Trelle
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMJonathan Wage
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 

Mais procurados (20)

Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
Model-Driven Software Development - Pretty-Printing, Editor Services, Term Re...
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Reflection with xamarin.forms
Reflection with xamarin.formsReflection with xamarin.forms
Reflection with xamarin.forms
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
 
03DOM.ppt
03DOM.ppt03DOM.ppt
03DOM.ppt
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
 
Lodash js
Lodash jsLodash js
Lodash js
 
Spring data
Spring dataSpring data
Spring data
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 

Semelhante a Data Binding Intro (Windows 8)

Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...Inhacking
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF BindingsEuegene Fedorenko
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012Amazon Web Services
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docxhoney725342
 
GraphQL in Symfony
GraphQL in SymfonyGraphQL in Symfony
GraphQL in SymfonyBernd Alter
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsCédric Hüsler
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworksEric Guo
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4Heather Rock
 
Configuring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture KorotchynConfiguring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture KorotchynABTO Software
 

Semelhante a Data Binding Intro (Windows 8) (20)

Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
Java and xml
Java and xmlJava and xml
Java and xml
 
GraphQL in Symfony
GraphQL in SymfonyGraphQL in Symfony
GraphQL in Symfony
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - Highlights
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworks
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
Configuring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture KorotchynConfiguring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture Korotchyn
 

Último

NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...Khaled Al Awadi
 
IPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceIPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceDragon Dream Bar
 
Team-Spandex-Northern University-CS1035.
Team-Spandex-Northern University-CS1035.Team-Spandex-Northern University-CS1035.
Team-Spandex-Northern University-CS1035.smalmahmud11
 
USA classified ads posting – best classified sites in usa.pdf
USA classified ads posting – best classified sites in usa.pdfUSA classified ads posting – best classified sites in usa.pdf
USA classified ads posting – best classified sites in usa.pdfsuperbizness1227
 
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdf
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdfMatt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdf
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdfMatt Conway - Attorney
 
Luxury Artificial Plants Dubai | Plants in KSA, UAE | Shajara
Luxury Artificial Plants Dubai | Plants in KSA, UAE | ShajaraLuxury Artificial Plants Dubai | Plants in KSA, UAE | Shajara
Luxury Artificial Plants Dubai | Plants in KSA, UAE | ShajaraShajara Artificial Plants
 
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical Trials
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical TrialsSalesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical Trials
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical TrialsFEXLE
 
Constitution of Company Article of Association
Constitution of Company Article of AssociationConstitution of Company Article of Association
Constitution of Company Article of Associationseri bangash
 
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot Report
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot ReportFuture of Trade 2024 - Decoupled and Reconfigured - Snapshot Report
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot ReportDubai Multi Commodity Centre
 
FEXLE- Salesforce Field Service Lightning
FEXLE- Salesforce Field Service LightningFEXLE- Salesforce Field Service Lightning
FEXLE- Salesforce Field Service LightningFEXLE
 
State of D2C in India: A Logistics Update
State of D2C in India: A Logistics UpdateState of D2C in India: A Logistics Update
State of D2C in India: A Logistics UpdateRedSeer
 
Special Purpose Vehicle (Purpose, Formation & examples)
Special Purpose Vehicle (Purpose, Formation & examples)Special Purpose Vehicle (Purpose, Formation & examples)
Special Purpose Vehicle (Purpose, Formation & examples)linciy03
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptseri bangash
 
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...Björn Rohles
 
zidauu _business communication.pptx /pdf
zidauu _business  communication.pptx /pdfzidauu _business  communication.pptx /pdf
zidauu _business communication.pptx /pdfzukhrafshabbir
 
How to Maintain Healthy Life style.pptx
How to Maintain  Healthy Life style.pptxHow to Maintain  Healthy Life style.pptx
How to Maintain Healthy Life style.pptxrdishurana
 
New Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9loNew Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9logalbokkahewagenitash
 
Potato Flakes Manufacturing Plant Project Report.pdf
Potato Flakes Manufacturing Plant Project Report.pdfPotato Flakes Manufacturing Plant Project Report.pdf
Potato Flakes Manufacturing Plant Project Report.pdfhostl9518
 
LinkedIn Masterclass Techweek 2024 v4.1.pptx
LinkedIn Masterclass Techweek 2024 v4.1.pptxLinkedIn Masterclass Techweek 2024 v4.1.pptx
LinkedIn Masterclass Techweek 2024 v4.1.pptxSymbio Agency Ltd
 
India’s Recommended Women Surgeons to Watch in 2024.pdf
India’s Recommended Women Surgeons to Watch in 2024.pdfIndia’s Recommended Women Surgeons to Watch in 2024.pdf
India’s Recommended Women Surgeons to Watch in 2024.pdfCIOLOOKIndia
 

Último (20)

NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...NewBase   24 May  2024  Energy News issue - 1727 by Khaled Al Awadi_compresse...
NewBase 24 May 2024 Energy News issue - 1727 by Khaled Al Awadi_compresse...
 
IPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceIPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best Service
 
Team-Spandex-Northern University-CS1035.
Team-Spandex-Northern University-CS1035.Team-Spandex-Northern University-CS1035.
Team-Spandex-Northern University-CS1035.
 
USA classified ads posting – best classified sites in usa.pdf
USA classified ads posting – best classified sites in usa.pdfUSA classified ads posting – best classified sites in usa.pdf
USA classified ads posting – best classified sites in usa.pdf
 
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdf
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdfMatt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdf
Matt Conway - Attorney - A Knowledgeable Professional - Kentucky.pdf
 
Luxury Artificial Plants Dubai | Plants in KSA, UAE | Shajara
Luxury Artificial Plants Dubai | Plants in KSA, UAE | ShajaraLuxury Artificial Plants Dubai | Plants in KSA, UAE | Shajara
Luxury Artificial Plants Dubai | Plants in KSA, UAE | Shajara
 
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical Trials
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical TrialsSalesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical Trials
Salesforce in Life Sciences - Best Ways to Leverage The CRM for Clinical Trials
 
Constitution of Company Article of Association
Constitution of Company Article of AssociationConstitution of Company Article of Association
Constitution of Company Article of Association
 
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot Report
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot ReportFuture of Trade 2024 - Decoupled and Reconfigured - Snapshot Report
Future of Trade 2024 - Decoupled and Reconfigured - Snapshot Report
 
FEXLE- Salesforce Field Service Lightning
FEXLE- Salesforce Field Service LightningFEXLE- Salesforce Field Service Lightning
FEXLE- Salesforce Field Service Lightning
 
State of D2C in India: A Logistics Update
State of D2C in India: A Logistics UpdateState of D2C in India: A Logistics Update
State of D2C in India: A Logistics Update
 
Special Purpose Vehicle (Purpose, Formation & examples)
Special Purpose Vehicle (Purpose, Formation & examples)Special Purpose Vehicle (Purpose, Formation & examples)
Special Purpose Vehicle (Purpose, Formation & examples)
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
 
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...
Meaningful Technology for Humans: How Strategy Helps to Deliver Real Value fo...
 
zidauu _business communication.pptx /pdf
zidauu _business  communication.pptx /pdfzidauu _business  communication.pptx /pdf
zidauu _business communication.pptx /pdf
 
How to Maintain Healthy Life style.pptx
How to Maintain  Healthy Life style.pptxHow to Maintain  Healthy Life style.pptx
How to Maintain Healthy Life style.pptx
 
New Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9loNew Product Development.kjiy7ggbfdsddggo9lo
New Product Development.kjiy7ggbfdsddggo9lo
 
Potato Flakes Manufacturing Plant Project Report.pdf
Potato Flakes Manufacturing Plant Project Report.pdfPotato Flakes Manufacturing Plant Project Report.pdf
Potato Flakes Manufacturing Plant Project Report.pdf
 
LinkedIn Masterclass Techweek 2024 v4.1.pptx
LinkedIn Masterclass Techweek 2024 v4.1.pptxLinkedIn Masterclass Techweek 2024 v4.1.pptx
LinkedIn Masterclass Techweek 2024 v4.1.pptx
 
India’s Recommended Women Surgeons to Watch in 2024.pdf
India’s Recommended Women Surgeons to Watch in 2024.pdfIndia’s Recommended Women Surgeons to Watch in 2024.pdf
India’s Recommended Women Surgeons to Watch in 2024.pdf
 

Data Binding Intro (Windows 8)

  • 1. 강남 DataBinding 스타일 Windows 8 앱개발자라면 꼭 알아야할 개발자가 알아야할 Binding
  • 2. Non-DataBinding vs. DataBinding <Grid> <Grid> <TextBlock x:Name=“TitleText”/> <TextBlock Text=“{Binding Title}”/> <TextBlock x:Name=“SubTitleText”/> <TextBlock Text=“{Binding SubTitle}”/> </Grid> </Grid> TitleText.Text = item.Title; this.DataContext = item; SubTitleText.Text = item.SubTitle;
  • 4. Non-DataBinding vs. DataBinding <Grid> <Grid> <HyperlinkButton /> <HyperlinkButton Content=“{Binding Title}”/> </Grid> </Grid> TitleText.Text = item.Title; this.DataContext = item; SubTitleText.Text = item.SubTitle; 컴파일 에러 발생!!! 컴파일 에러 없음 UI와 코드의 분리 개발자와 디자이너 업무영역의 분리 PEACE!
  • 5. 이번 앨범 타이틀 곡이 뭐야?
  • 10. FrameworkElement.DataContext 거의 모든 UI는 FrameworkElement
  • 11. 가정 class Chart + Album FirstAlbum class Album + List<Album> Albums + string CoverArt + string Name + Artist Artist class Artist + string ProfilerImage + string Name
  • 12. 자식에게 상속하는 DataContext Visual Tree Grid(LayoutRoot) <Grid x:Name=“LayoutRoot” Image DataContext=“{Binding TopAlbum}”> <Image Source=“{Binding CoverArt}”/> TextBlock <TextBlock Text=“{Binding Title}”/> Grid <StackPanel DataContext=“{Binding Artist}”> Image <Image Source=“{Binding ProfileImage}”/> TextBlock <TextBlock Text=“{Binding Name}”/> </StackPanel> </Grid>
  • 13. 자식에게 상속하는 DataContext Visual Tree Grid(LayoutRoot) <Grid x:Name=“LayoutRoot” Image DataContext=“{Binding TopAlbum}”> <Image Source=“{Binding CoverArt}”/> TextBlock <TextBlock Text=“{Binding Title}”/> Grid <StackPanel> Image <Image Source=“{Binding Artist.ProfileImage}”/> TextBlock <TextBlock Text=“{Binding Artist.Name}”/> </StackPanel> </Grid>
  • 14. DataContext 주입법 In C# var chart = GetKPopChart(); this.DataContext = chart; In XAML <Page> <Page> <Page.Resources> <Page.DataContext> <models:KPopChart x:Key=“Chart” /> <models:KPopChart x:Key=“Chart” /> </Page.Resources> </Page.DataContext> <Grid DataContext=“{StaticResource Chart}”> <Grid > ….. ….. </Grid> </Grid> </Page> </Page>
  • 16. 문법 • Binding – Text="{Binding Title}" • Path (생략가능) – Text=“{Binding Path=Title}” • Source – Text=“{Binding Name, Source={StaticResource MyViewModel}}” • Converter – Text=“{Binding PublishDate, Converter={StaticResource FamiliarDateString}}” • ConverterParameter – Text=“{Binding Price, Converter={StaticResource CurrencyConverter}, ConverterParameter={0:C2}}”
  • 17. {Binding } • DataContext 자기 자신! <TextBlock Text=“{Binding }” />
  • 19. ItemsControl 가족 • ListView Control • GridView • FlipView • ListBox ItemsControl .ItemsSource 프로퍼티가 여기 정의 • ComboBox Selector ListViewBase FlipView ListBox ComboBox ListView GridView
  • 20. ItemsControl에서 DataContext 분배 CS에서 var artists = new List<Artist>() { 싸이 new Artist() { Name = “싸이”, CoverArt=“…”}, new Artist() { Name = “아이 유”, CoverArt=“…”}, 아이유 new Artist() { Name = “싸이”, CoverArt=“…”}, new Artist() { Name = “아이 유”, CoverArt=“…”}, } 싸이 this.Artists = artist; …. XAML에서 아이유 <ListView ItemsSource=“{Binding Artists}” />
  • 21. ItemTemplate과 DataContext new Artist() { 싸이 Name = “싸이”, CoverArt=“…”, } <ListView.ItemTemplate> <DataTemplate> ItemsSource의 인스턴스 하나가 <Grid> ListViewItem 하나의 DataContext가 <StackPanel> 된다. <Image Source=“{Binding CoverArt}” /> <TextBlock Text=“{Binding Name}” /> </StackPanel> </Grid> </DataTemplate> </ListView.ItemTemplate>
  • 22. In the hood ItemsControl의 virtual PrepareContainerForItemOverride(…) 에서 protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { var contentControl = element as ContentControl; contentControl.ContentTemplate = this.ItemTemplate; contentControl.DataContext = item; }
  • 24. 약속 컨트롤은 INotifyPropertyChanged.PropertyChanged를 구독합니다. 컨트롤은 INotifyCollectionChanged.CollectionChanged를 구독합니다. Common/BindableBase.cs 에서 public abstract class BindableBase : INotifyPropertyChanged System.Collections.ObjectModel public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged
  • 25. 이미 구현되어 있는 것 DataModel/SampleDataSource.cs에서 public abstract class SampleDataCommon : App4.Common.BindableBase 프로퍼티 예 : Title private string _title = string.Empty; public string Title { get { return this._title; } set { this.SetProperty(ref this._title, value); } } In the Hood protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null) { if (object.Equals(storage, value)) return false; storage = value; this.OnPropertyChanged(propertyName); return true; }
  • 26. List<Artist> vs. ObservableCollection<Artist> this.Artist.Add(new Artist()); this.Artist.Add(new Artist()); 싸이 싸이 아이유 아이유 싸이 싸이 아이유
  • 28. 어떤 필요, 어떤 니즈? public List<string> Artists { get; set; } … Artists = new List<string>() { “싸이”, “아이유”, }; 너랑 나랑 강남스타일 싸이, 아이유
  • 29. 샘플 ArtistConverter namespace MyApp { public class ArtistConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { // null 체크, value가 Ienumerable 타입이 아닐 때 예외처리 (생략) var list = value as IEnumerable; StringBuilder sb = new StringBuilder(); foreach (var item in list) { if (sb.Length > 0) sb.Append(“, “); sb.Append((string)item); } return sb.ToString(); } } }
  • 30. 사용법 인스턴스 생성 (어딘가에) -> 바인딩 식에서 잘 사용 In MyView.xaml (or App.xaml) <Page> <Page.Resources> <conv:ArtistConverter x:Key=“ArtistConverter”/> </Page.Resources> <Grid x:Name=“LayoutRoot”> … <TextBlock Text=“{Binding Artists, 너랑 나랑 강남스타일 Converter={StaticResource ArtistConverter}”/> 싸이, 아이유 </Grid> </Page>
  • 33. GridApp 샘플 프로젝트에서 GroupedItemsPage.xaml.cs에서 protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // TODO: Create an appropriate data model for your problem domain to replace the sample data var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter); this.DefaultViewModel["Groups"] = sampleDataGroups; } GroupedItemsPage.xaml에서 <common:LayoutAwarePage x:Name="pageRoot" x:Class="App4.GroupedItemsPage" DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}“ … <CollectionViewSource x:Name="groupedItemsViewSource" Source="{Binding Groups}"