using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace Sample
{
public class ListViewBehavior
{
// ListViewに登録するスタイルのキー
private static readonly Type STYLE_KEY = typeof(TextBlock);
// ListViewに登録するスタイルのベース
private static readonly Style APPLY_STYLE_BASE;
static ListViewBehavior()
{
// スタイルを組み立てる
APPLY_STYLE_BASE = new Style(typeof(TextBlock));
// TextTrimmingの設定
APPLY_STYLE_BASE.Setters.Add(
new Setter(TextBlock.TextTrimmingProperty, TextTrimming.CharacterEllipsis));
// ToolTipの設定
APPLY_STYLE_BASE.Setters.Add(
new Setter(
TextBlock.ToolTipProperty,
new Binding
{
RelativeSource = new RelativeSource(RelativeSourceMode.Self),
Path = new PropertyPath(TextBlock.TextProperty)
}));
// 一応固めとく
APPLY_STYLE_BASE.Seal();
}
[AttachedPropertyBrowsableForType(typeof(ListView))]
public static bool GetEnableTextTrimming(DependencyObject obj)
{
return (bool)obj.GetValue(EnableTextTrimmingProperty);
}
[AttachedPropertyBrowsableForType(typeof(ListView))]
public static void SetEnableTextTrimming(DependencyObject obj, bool value)
{
obj.SetValue(EnableTextTrimmingProperty, value);
}
// Using a DependencyProperty as the backing store for EnableTextTrimming. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnableTextTrimmingProperty =
DependencyProperty.RegisterAttached("EnableTextTrimming", typeof(bool), typeof(ListViewBehavior), new UIPropertyMetadata(false, EnableTextTrimmingChanged));
private static void EnableTextTrimmingChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var listView = sender as ListView;
if (listView == null) return;
// リソースにスタイルが登録されていれば取り除く
if (listView.Resources.Contains(STYLE_KEY))
{
listView.Resources.Remove(STYLE_KEY);
}
// trueが設定されたら、スタイルを設定する
var value = (bool)e.NewValue;
if (value)
{
listView.Resources.Add(STYLE_KEY, new Style(typeof(TextBlock), APPLY_STYLE_BASE));
}
}
}
}
<!-- xmlns:local="clr-namespace:Sample"を何処かでしてること -->
<ListView
local:ListViewBehavior.EnableTextTrimming="True">