かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[C#][WPF]WPFでカレンダー表示する部品って無いんだよね

カレンダーが無いなら作ればいいじゃない?
というわけで作ってみよう。

超汎用的なものを作るのはめんどくさいので、仕様はかなり絞ってみようと思う。

  1. 年月日をDateTime型で指定すると、その月のカレンダーを表示して、指定した日を選択状態にする
  2. 曜日は日曜日はじまり
  3. もちろん選択された日付をDateTime型で取得できる

前の月とか次の月や翌年、前月はとりあえずスルー。
とりあえず、日付群の中から1つ選ぶということでListBoxでいいだろう。

30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2

こんな感じに表示させたいので、リストボックスのテンプレートをいじる。
カラムが7つのUniformGridを2つほどStackPanelに乗せる。
1つ目のGridには、日~土までを。
2つ目のGridはIsItemsHostをTrueにして、ListBoxのItemを表示するのに使う。

		<ListBox Name="calendar">
			<ListBox.Resources>
				<Style TargetType="{x:Type TextBlock}">
					<Setter Property="TextAlignment" Value="Right" />
				</Style>
			</ListBox.Resources>
			<ListBox.Template>
				<ControlTemplate TargetType="{x:Type ListBox}">
					<StackPanel>
						<UniformGrid Columns="7">
							<TextBlock Text="日" />
							<TextBlock Text="月" />
							<TextBlock Text="火" />
							<TextBlock Text="水" />
							<TextBlock Text="木" />
							<TextBlock Text="金" />
							<TextBlock Text="土" />
						</UniformGrid>
						<UniformGrid Columns="7" IsItemsHost="True">
						</UniformGrid>
					</StackPanel>
				</ControlTemplate>
			</ListBox.Template>
		</ListBox>

これをWindowに乗せると、こんな感じになる。

image

とりあえずいい感じ。
んで、ListBoxのDataContextにDateTimeを設定すると、その月のカレンダーが表示されるようにしてみようと思う。
というわけで、DateTimeをもとに、その月(と間を埋めるために必要な前月と翌月の数日)の日付の列挙に変換するコンバータを用意する。

namespace WpfCalendar
{
    public class DateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = (DateTime)value;
            var days = (from day in Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month))
                        select new DateTime(date.Year, date.Month, day)).ToList();
            var first = days.First();
            for (int i = 0; i < (int)first.DayOfWeek; i++)
            {
                days.Insert(0, days.First().AddDays(-1));
            }

            var last = days.Last();
            for (int i = 0; i < 6 - (int)last.DayOfWeek; i++)
            {
                days.Add(days.Last().AddDays(1));
            }

            return days;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}

このコンバータを使ってListBoxのItemsSourceにDataContextをバインドする。

		<ListBox Name="calendar">
			<ListBox.ItemsSource>
				<Binding>
					<Binding.Converter>
						<c:DateTimeConverter xmlns:c="clr-namespace:WpfCalendar" />
					</Binding.Converter>
				</Binding>
			</ListBox.ItemsSource>
			<ListBox.Resources>
				<Style TargetType="{x:Type TextBlock}">
					<Setter Property="TextAlignment" Value="Right" />
				</Style>
			</ListBox.Resources>
			<ListBox.Template>
				<ControlTemplate TargetType="{x:Type ListBox}">
					<StackPanel>
						<UniformGrid Columns="7">
							<TextBlock Text="日" />
							<TextBlock Text="月" />
							<TextBlock Text="火" />
							<TextBlock Text="水" />
							<TextBlock Text="木" />
							<TextBlock Text="金" />
							<TextBlock Text="土" />
						</UniformGrid>
						<UniformGrid Columns="7" IsItemsHost="True">
						</UniformGrid>
					</StackPanel>
				</ControlTemplate>
			</ListBox.Template>
		</ListBox>

この時点で実行すると、↓のような感じになる。

image

段々それっぽくなってきてるかな。
後は、ListBoxのItemTemplateとItemContainerStyleで日付部分を右詰めで表示してあげる。

		<ListBox Name="calendar"
		    xmlns:sys="clr-namespace:System;assembly=mscorlib">
			<ListBox.ItemsSource>
				<Binding>
					<Binding.Converter>
						<c:DateTimeConverter xmlns:c="clr-namespace:WpfCalendar" />
					</Binding.Converter>
				</Binding>
			</ListBox.ItemsSource>
			<ListBox.Resources>
				<Style TargetType="{x:Type TextBlock}">
					<Setter Property="TextAlignment" Value="Right" />
				</Style>
			</ListBox.Resources>
			<ListBox.Template>
				<ControlTemplate TargetType="{x:Type ListBox}">
					<StackPanel>
						<UniformGrid Columns="7">
							<TextBlock Text="日" />
							<TextBlock Text="月" />
							<TextBlock Text="火" />
							<TextBlock Text="水" />
							<TextBlock Text="木" />
							<TextBlock Text="金" />
							<TextBlock Text="土" />
						</UniformGrid>
						<UniformGrid Columns="7" IsItemsHost="True">
						</UniformGrid>
					</StackPanel>
				</ControlTemplate>
			</ListBox.Template>
			<ListBox.ItemContainerStyle>
				<Style TargetType="{x:Type ListBoxItem}">
					<Setter Property="HorizontalContentAlignment" Value="Right" />
				</Style>
			</ListBox.ItemContainerStyle>
			<ListBox.ItemTemplate>
				<DataTemplate DataType="{x:Type sys:DateTime}">
					<TextBlock Text="{Binding Day}" />
				</DataTemplate>
			</ListBox.ItemTemplate>
		</ListBox>

実行すると、カレンダーっぽくなってきた。

image

今日は眠いのでここまで。

投稿日時 : 2008年1月20日 3:12

Feedback

# [C#][WPF]カレンダーを作ってみよう 2008/01/20 12:03 かずきのBlog

[C#][WPF]カレンダーを作ってみよう

# re: [C#][WPF]WPFでカレンダー表示する部品って無いんだよね 2008/01/21 1:28 nsharp

はじめまして。( ゚д゚)ノ

日付の列挙に関して:
このサンプルの場合、クエリー実行は後まわしにした方がロジックがすっきりしますよ。

こんな感じです。

  var date = (DateTime) value;

  // 該当月の1日と末日
  var firstDay = new DateTime(date.Year, date.Month, 1);
  var lastDay = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

  // カレンダー表示の開始日と終了日
  var startDate = firstDay.AddDays(DayOfWeek.Sunday - firstDay.DayOfWeek);
  var endDate = lastDay.AddDays(DayOfWeek.Saturday - lastDay.DayOfWeek);

  return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(n => startDate.AddDays(n));

# re: [C#][WPF]WPFでカレンダー表示する部品って無いんだよね 2008/01/21 6:35 かずき

>nsharpさん
確かにそうですね~。
断然見やすくなりますね(^^

# re: [C#][WPF]WPFでカレンダー表示する部品って無いんだよね 2008/01/21 14:02 nsharp

LINQフル活用で、ということでしたら、無限リストを相手にしてみるのもおもしろいかもしれません。

  static IEnumerable<DateTime> Past(this DateTime d) {
    while (true) {
      d = d.AddDays(-1);
      yield return d;
    }
  }

  static IEnumerable<DateTime> Future(this DateTime d) {
    while (true) {
      d = d.AddDays(1);
      yield return d;
    }
  }

んで、

  var date = (DateTime) value;

  // 該当月の1日と末日
  var firstDay = new DateTime(date.Year, date.Month, 1);
  var lastDay = firstDay.AddMonths(1).AddDays(-1);

  var past = date.Past().TakeWhile(d => d >= firstDay || d.DayOfWeek != DayOfWeek.Saturday).Reverse();
  var present = Enumerable.Repeat(date, 1);
  var future = date.Future().TakeWhile(d => d <= lastDay || d.DayOfWeek != DayOfWeek.Sunday);

  return past.Concat(present).Concat(future);

まあ、お遊びということで・・・。

# ???C#????????????????????????????????????????????????1???WPF??? | ???????????? 2011/05/31 10:45 Pingback/TrackBack

???C#????????????????????????????????????????????????1???WPF??? | ????????????

# sac longchamp pas cher 2012/10/17 23:14 http://www.sacslongchamppascher2013.com

You have brought up a very superb details , thankyou for the post.

# uDPIVLJOCkxnXdMQuyy 2014/08/28 1:31 http://crorkz.com/

lA3wCM Hello, you used to write great, but the last several posts have been kinda boring??? I miss your great writings. Past several posts are just a little out of track! come on!

# For sale in las vegas 2018/01/08 3:47 buying cheap online

Uk cheap http://quickfinds.in/user/profile/71137 Can I buy over the counter in philippines.

# Buy next day delivery 2018/01/08 4:07 buying online canada

Without a doctor prescription uk http://mercadoloko.com.br/user/profile/97588 cost of in us.

# Where can I buy tablets 2018/01/08 9:45 generic low cost

where can i buy cheap pills http://www.capebretoncountryclub.com/component/k2/itemlist/user/67786 buy online safely.

# Generic best price 2018/01/08 11:26 usa buy

best prices for generic http://www.satextiles.co.za/?option=com_k2&view=itemlist&task=user&id=36073 order online next day delivery.

# Cost of in new zealand 2018/01/08 18:48 buy in store

lowest price http://3drus.ru/user/DonnieDavies/ buy nz.

# What does a pill cost 2018/01/09 2:58 Buy online overnight shipping

pills for sale in south africa http://kinosrulad.com/user/MerryY2786001503/ can i buy online in uk.

# Peut ton acheter sans ordonnance 2018/01/09 19:31 Medicaments En Ligne

Comment acheter duen ligne http://medicamentsonline.life/ranitidina.html prix duen Suisse.

# drogist kopen 2018/01/10 4:27 Bestellen Pnline

Kopen in winkel rotterdam prijzen, http://online-medicijnen-bestellen.life/nimotop.html , online bestellen zonder recept te koop.

# koop prijs 2018/01/11 23:03 Medicijnen Online

Wat kost bij de apotheek den haag, http://onlinemedicijnenbestellen.life/sinequan.html , veilig kopen goedkoop.

# i Sverige Danmark 2018/01/12 0:34 forste-apotek-norge life

online Norge, http://forste-apotek-norge.life/viramune.html , lovlig online.

# priser apoteket 2018/01/12 1:18 APOTEKVARER PA NETTET

bestall billigt, http://apotekvarerpanettet.life/aciclovir.html , receptfritt köp.

# elad&amp;#225;s n&amp;#233;lk&amp;#252;l 2018/01/12 5:14 gyogyszertar-hu life

rendelés online, http://gyogyszertar-hu.life/dostinex.html - eladás.

# apoteket g&amp;#246;teborg 2018/01/12 10:56 apotekvarer-pa-nettet

receptfritt spanien pris, http://apotekvarerpanettet.life/vasotec.html , Sverige pris.

# on-line &amp;#225;rfolyamok 2018/01/12 11:06 gyogyszertar online hu life

vásárlás azonnal eladó, http://gyogyszertar-online-hu.life/estrace.html - recept nélkül árfolyamok.

# alternatief drogist kopen 2018/01/12 11:14 Online Zonder Recept

Kopen in belgie frankrijk, http://onlineapothekerzonderrecept.life/januvia.html , kopen winkel nederland.

# kosten holland 2018/01/12 16:40 Zonder Recept Online

Kopen den haag kopen, http://online-apotheker-zonder-recept.life/tetracycline.html , kopen winkel belgie.

# kan man kj&amp;#248;pe uten resept i Spania pris 2018/01/12 17:42 Apotek Norge

apotek Norge Spania, http://apotek-nettbutikk-norge.life/aldactone.html , kjøp Norge.

# apotek Danmark G&amp;#248;teborg 2018/01/13 1:37 APOTEK-NORWAY.life

Danmark online, http://apotek-norway.life/retin-a.html , selge til salgs.

# generisk billigt priser 2018/01/13 3:16 billige-apotekvarer.life

apotek pris, http://apotekvarerpanettet.life/topamax.html , lagligt pris.

# pris apotek malm&amp;#246; 2018/01/13 3:22 apotekvarerpanett life

tabletter göteborg, http://apotekvarerpanettet.life/sarafem.html , köpa i Sverige göteborg.

# bestellen voorschrift 2018/01/13 5:28 Nederland Apotheker Online

Amsterdam kosten, http://online-apotheker-nederland.life/propranolol.html , pillen kopen nederland.

# bestille nett 2018/01/13 8:58 apoteknorway life

beste sted å kjøpe Sverige, http://apoteknorway.life/amaryl.html , salg bergen.

# prijsvergelijking winkel 2018/01/13 11:21 Apotheek Zonder Recept

Kopen in belgie prijs, http://onlineapotheekzonderrecept.life/nimotop.html , kopen zonder recept apotheek kosten.

# v&amp;#225;s&amp;#225;rl&amp;#225;s elad&amp;#243; 2018/01/13 15:28 GYOGYSZERTAR ONLINE

árak, http://gyogyszertar-online.life/methotrexate.html - budapest azonnal.

# te koop bij apotheek nederland 2018/01/13 16:42 online-apotheek-zonder-recept.life

Kopen in frankrijk belgie, http://online-apotheek-zonder-recept.life/plavix.html , veilig kopen nederland.

# kj&amp;#248;p online i Norge Oslo 2018/01/13 18:15 apotek norge online life

prissammenligning Danmark, http://apotek-norge-online.life/zocor.html , kostnaden nett.

# generic uk online 2018/01/13 19:11 SVERIGE APOTEK PA NATET

online shop, http://apotekvarerpanettet.life/myambutol.html , köpa tabletter.

# pris tabletter 2018/01/14 3:02 Apotek Norge Online

uten resept i Sverige pris, http://apoteknorgeonline.life/rogaine.html , kjøpe Norge pris.

# s&amp;#228;ljes billigt 2018/01/14 4:43 SVERIGE APOTEK PA NATET

shop malmö, http://apotekvarerpanettet.life/carbozyne.html , lagligt säkert.

# gy&amp;#243;gyszer elad&amp;#243; 2018/01/14 7:41 gyogyszertarban-online

árösszehasonlító gyógyszer, http://gyogyszertarban-online.life/stromectol.html - megvesz recept.

# online shop pris 2018/01/14 8:30 apotek pa natet sverige

billiga generic, http://apotekvarerpanettet.life/femara.html , kostar pris.

# best&amp;#228;lla lagligt priser 2018/01/14 19:18 Apotek Pa Natet Sverige

online shop USA, http://apotekvarerpanettet.life/benicar.html , till salu kostnad.

# kapsler til salgs 2018/01/14 19:41 norge apotek life

pris apotek Sverige København, http://norge-apotek.life/fluoxetine.html , kjøp uten resept Tyskland.

# Generic new zealand 2018/01/14 20:56 safe place to buy online

Non prescription online http://www.andersfray.com/blog/?page_name=hyzaar Order online usa.

# kj&amp;#248;p uten resept nett 2018/01/15 0:46 norgeapotek life

i Sverige uten resept Tyskland, http://norgeapotek.life/capoten.html , kjøp uten resept Norge.

# Cheapest generic canada 2018/01/16 1:03 pills cheap

typical price of http://www.jimsbigthings.com/?page_name=femara buy in singapore.

# Natural new zealand 2018/01/16 7:08 next day delivery

cheap new zealand http://www.noraleduc.com/?page_name=metformin generic usa.

# comprar en farmacias sin receta 2018/01/22 7:26 WWW.GWSISECURITY.COM

Donde conseguir en España http://www.gwsisecurity.com/fig/data/farmacia/destolit.html generica farmacia.

# G&amp;#252;nstig kaufen ohne rezept 2018/01/22 8:11 Samara

handelsnamen osterreich http://samararestoration.com/misc/farbtastic/apotheke/nyzoc.html preis mit rezept.

# comprar venezuela 2018/01/22 13:40 SUPONCREATIVE

Donde puedo comprar generico en mexico http://www.suponcreative.com/clients/gw/image-book/js/farmacia/aramix.html se vende sin receta Peru.

# conseguir sin receta mexico 2018/01/22 13:40 HANDLEDESIGNS.COM

Costo in francia http://handledesigns.com/img/farmacia/sitran.html comprar seguro España.

# Generika online apotheke 2018/01/22 16:25 SERVICES

tabletten bewertung http://www.vedicastrologyservices.com/_fpclass/apotheke/azur.html granulat kosten.

# Generika &amp;#246;sterreich 2018/01/22 17:42 BLAKE

Tabletten wirkungsweise http://blakemarymor.com/DROPBOX/apotheke/sarcop.html Behandeling bestellen.

# donde comprar seguro 2018/01/22 19:42 High Desert Pinto Horse

Pastillas cuanto cuesta en mexico http://highdesertpintohorse.org/machform/data/form_10940/farmacia/liporex.html se puede comprar sin receta en farmacias en Chile.

# se vende sin receta en argentina 2018/01/22 19:43 mdaane

Como comprar sin receta medica http://mdaane.com/images/blogImages/farmacia/misol.html venta sin receta Argentina.

# Generika rezeptfrei &amp;#252;berweisung 2018/01/22 20:46 Carlsbad

apotheke schweiz http://carlsbadridersco.com/shop/media/apotheke/nodon.html antibabypille gunstig kaufen.

# comprar sin receta en tenerife 2018/01/23 1:32 CYPRESS ASSISTANCE

Comprar en estados unidos http://www.cypressassistance.org/wp-content/uploads/2017/04/farmacia/ateplax.html comprar en sevilla.

# por internet chile 2018/01/23 1:32 HARRISON1966.COM

Precio paraguay http://www.harrison1966.com/gallery/farmacia/curam.html comprar seguro por internet.

# Kaufen deutschland paypal 2018/01/23 8:28 SKANSAILCLUB

gunstig online kaufen http://skansailclub.com/sites/default/files/color/apotheke/clobetasol.html online kaufen ohne rezept paypal.

# Deutschland 2018/01/23 9:03 chronovalve.com

rezeptfrei online kaufen http://chronovalve.com/ezg_data/apotheke/thombran.html online kaufen ohne rezept gunstig.

# Rezeptfrei billig 2018/01/23 9:08 Dana X Zheng

gunstig bestellen per nachnahme http://danazheng.com/assets/fonts/apotheke/lanacine.html rezeptfreie alternative.

# Kosten holland 2018/01/23 15:44 Snap Photo

brausetabletten preis http://snapapplephoto.com/oldsite/images/apotheke/captobeta-comp.html online auf rechnung bestellen.

# necesita receta medica 2018/01/23 17:18 Jessica Straus

Puedo comprar sin receta medica en España http://www.jessica-straus.com/system/expressionengine/cache/farmacia/flibanserin.html conseguir sin receta.

# conseguir en ecuador 2018/01/23 22:10 METALNEX.COM

Venta en carabobo http://www.metalnex.com/wp/design/farmacia/carvedil.html hace falta receta para comprar en la farmacia.

# Preiswert online kaufen 2018/01/24 0:21 golfscorecard.net

ohne kreditkarte http://golfscorecard.net/slideshowpro/apotheke/solupred.html Bestellen nederland.

# Tabletten frauen 2018/01/24 1:14 Swiss Air 111

Online kaufen per uberweisung http://www.swissair111.org/ubb2/apotheke/simvastatin.html bijwerkingen tabletten generiek.

# comprar generica en espa&amp;#241;a 2018/01/24 4:14 banglaunited

Comprar online contrareembolso http://www.banglaunited.com/farmacia/bicalutamide.html donde conseguir sin receta.

# Generikum ohne rezept 2018/01/24 9:35 TEPOZTLANVACATIONRENTALS

brausetabletten preis http://tepoztlanvacationrentals.com/llcj/cache/apotheke/lopecia.html Dapoxetin rezeptfrei.

# Ampullen kosten 2018/01/24 9:37 Crossroads Church

in holland kaufen http://www.gocrossroads.net/oldsite/cgi-bin/bk/active_guestbook_backups/apotheke/starlix.html online kaufen per paypal.

# Price comparison usa 2018/02/14 20:00 Generic Pharmacies

pills online uk http://genericpharmacies.review medication price.

# Generic cost australia 2018/02/14 20:39 Medications Online

generic online next day delivery http://medications-online.men buy generic cheap.

# Generic for sale uk 2018/02/15 16:37 medications online

canada for sale http://medicationsonline.men For sale in canada.

# Purchasing online uk 2018/02/17 7:52 ONLINE MEDICATIONS

buy over the counter in australia http://onlinemedications.men/ cheap australia.

# pierce county georgia public records 2018/03/26 22:19 arrest lookup

Pa criminal background checks for employment, http://arrest-lookup.science/educational-background-check-dui-6-years-ago.html york county pa public arrest records.

# hamilton county ohio criminal background check 2018/03/27 0:06 background-checking science

Inmate lookup county jail, http://background-checking.science/government-background-check-company-does-it-take.html oregon attorney general public records manual.

# best pre-employment background checks 2018/03/27 7:46 checks background

Lancaster county court records lincoln nebraska, http://affordable-background-checks.science/obtain-background-check-bill-senate-gun.html united states prison inmate search.

# free arrest records colorado springs 2018/03/27 11:20 check background

Eeoc criminal background discrimination, http://background-check-yourself.science/property-background-check-questions-sample-employee.html search public records in hillsborough county florida.

# arrest records public information 2018/03/28 11:30 background-check-usa

Pre employment background check salary, http://background-check-usa.science/government-criminal-records-richland-county-oh.html fairfield county ct court records search.

# realtor background check minnesota state 2018/03/28 11:38 check background

New york state public records marriage license, http://background-check-tenants.science/inmate-search-by-name-volusia-county-florida-jail.html jacksonville florida criminal records search.

# what to expect in a police background check 2018/03/28 14:19 advance-background-checks.science

Criminal history search in texas, http://advance-background-checks.science/background-check-by-name-how-long-job-in-sap.html search criminal records alberta.

# form for background check ohio free 2018/03/29 7:20 background check tenant science

Buncombe county arrest records online, http://background-check-tenant.science/where-can-i-get-criminal-records-jefferson-county-tx.html free public records search pinellas county.

# background check fees vendors 2018/03/29 10:56 accurate background screening science

Dps computerized criminal history verification form spanish, http://accurate-background-screening.science/how-do-you-tweet-on-someone-else39s-twitter-page.html jackson county north carolina public records search.

# new jersey public records 2018/03/29 19:27 background check accurate

Free criminal background reports, http://accurate-background-checks.science/background-check-investigator-before-offer-california.html prison background check.

# information on someone solar system 2018/03/30 18:17 background-check-site

Free criminal records for arizona, http://background-check-site.science/government-public-records-queens-ny.html warrant check collin county.

# fbi criminal background check status 2018/04/01 20:40 access-background-checks stream

Criminal record report abbreviations, http://access-background-checks.stream public arrest records alabama free.

# best jail inmate search los angeles calif 2018/04/03 20:32 http://access-background-checks.stream

Misdemeanor background check for employment, http://advanced-background-check.science/drug-and-background-check-for-landlords.html pre employment screening deutsche bank.

タイトル  
名前  
Url
コメント