Instantly share code, notes, and snippets.
Created Dec 17, 2013
Windows PhoneのApplication Barのバインディングサンプル。長くなるのでコマンドは省略。コマンドはprismのソースを参照するとよいです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Phone.Controls; | |
using Microsoft.Phone.Shell; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows; | |
using System.Windows.Input; | |
using System.Windows.Interactivity; | |
namespace BindableSample | |
{ | |
public class BindToApplicationBarIconButtonBehavior : Behavior<PhoneApplicationPage> | |
{ | |
public BindToApplicationBarIconButtonBehavior() : base() { } | |
/// <summary> | |
/// ビヘイビアーを定義する際に対象の Text と同じ値を設定してください。 | |
/// </summary> | |
public string TargetItemStaticText { get; set; } | |
/// <summary> | |
/// テキストを取得または設定します。 | |
/// </summary> | |
public string Text | |
{ | |
get { return (string)GetValue(TextProperty); } | |
set { SetValue(TextProperty, value); } | |
} | |
public static readonly DependencyProperty TextProperty = | |
DependencyProperty.Register("Text", typeof(string), typeof(BindToApplicationBarIconButtonBehavior), new PropertyMetadata(TextChangedHandler)); | |
protected override void OnAttached() | |
{ | |
base.OnAttached(); | |
this.ChangeText(); | |
} | |
static void TextChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e) | |
{ | |
((BindToApplicationBarIconButtonBehavior)sender).OnTextChanged(); | |
} | |
void OnTextChanged() | |
{ | |
if (this.AssociatedObject == null) return; // before attached | |
this.ChangeText(); | |
} | |
void ChangeText() | |
{ | |
if (this.Text == null) throw new InvalidOperationException("Text が設定されていません。"); | |
var buttons = this.AssociatedObject.ApplicationBar.Buttons | |
.OfType<ApplicationBarIconButton>() | |
.Where(x => x.Text == this.TargetItemStaticText); | |
if (!buttons.Any()) throw new InvalidOperationException("TargetItemStaticText が一致するボタンが見つかりません。"); | |
if (buttons.Count() > 1) throw new InvalidOperationException("他のアイテムと同じテキストを設定することはできません。"); | |
buttons.First().Text = this.Text; | |
this.TargetItemStaticText = this.Text; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment