[WPF] Comment se binder à un contrôle Run ?
Pour afficher du texte, WPF (Windows Presentation Foundation) propose un certains nombres de contrôles (TextBlock, Label, etc...).
Parmis ces contrôles, il existe le contrôle "Run" qui possède les mêmes caractéristiques qu'un TextBlock mais qui ne peut pas être positionné: on l'utilise donc via une imbrication dans un TextBlock.
Ce contrôle, qui possède une propriété Text permettant de spécifier le texte à afficher, est très intéressant mais pose un problème: cette propriété Text n'est pas une DependencyProperty autrement dit, il n'est pas possible de se binder dessus...
Pour corriger ce problème, je vous propose une implémentation d'une classe, héritant de Run, proposant justement une proriété que vous allez pouvoir binder.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Documents;
namespace WPFDeveloperTools.Controls.BindableRunControl
{
/// <summary>
/// BindableRunControl is a control that inherit from the Run control but which have a bindable Text Property.
/// </summary>
public class BindableRunControl : Run
{
#region Constructors
public BindableRunControl()
: base()
{
}
#endregion
#region Properties
/// <summary>
/// Property to use to specify the text that need to be binded.
/// </summary>
public string BindableText
{
get { return (string)GetValue(BindableTextProperty); }
set { SetValue(BindableTextProperty, value); }
}
public static readonly DependencyProperty BindableTextProperty =
DependencyProperty.Register("BindableText", typeof(string), typeof(BindableRunControl), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnBindableTextChanged)));
#endregion
private static void OnBindableTextChanged(DependencyObject element, DependencyPropertyChangedEventArgs arg)
{
string TextToBind = arg.NewValue as string;
if (!string.IsNullOrEmpty(TextToBind))
{
BindableRunControl control = element as BindableRunControl;
if (control != null)
{
control.Text = TextToBind;
}
}
}
}
}
J'espère que cela vous sera utile au cours de vos projets 
Pour informations, ce contrôle fait partie d'un ToolKit que j'avais mis à disposition sur Internet (via Codeplex) et que j'ai dû enlever mais qui, je l'espère, fera sa réapparition très bientôt.
A+
Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :