Skip to content

Instantly share code, notes, and snippets.

@KatsuYuzu
Created December 17, 2013 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuYuzu/8008997 to your computer and use it in GitHub Desktop.
Save KatsuYuzu/8008997 to your computer and use it in GitHub Desktop.
Windows PhoneのApplication Barのバインディングサンプル。長くなるのでコマンドは省略。コマンドはprismのソースを参照するとよいです。
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