Code behind

De Banane Atomic
Aller à la navigationAller à la recherche

Créer un menu contextuel

Csharp.svg
var cm = new ContextMenu();
var mt = new MenuItem();
mt.Header = "Titre";
mt.Click += mt_Click;
cm.Items.Add(mt);

var textBox = new TextBox()
{
    ContextMenu = cm
};

void mt_Click(object sender, RoutedEventArgs e)
{
    var menuItem = (MenuItem)e.Source;
    var contextMenu = (ContextMenu)menuItem.Parent;
    var textbox = contextMenu.PlacementTarget as TextBox;
}

Appeler un event

Csharp.svg
// Lance l'event LostFocus pour permettre la validation de la TextBox
textBox.RaiseEvent(new RoutedEventArgs(TextBox.LostFocusEvent));

DataTemplate

Csharp.svg
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
var label = new FrameworkElementFactory(typeof(Label));
label.SetValue(Label.ContentProperty, "texte");
stackPanel.AppendChild(label);

var dataTemplate = new DataTemplate();
dataTemplate.VisualTree = stackPanel;

ControlTemplate

Csharp.svg
var itemsPresenter = new FrameworkElementFactory(typeof(ItemsPresenter));
var textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.TextProperty, "...");

var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.AppendChild(itemsPresenter);
stackPanel.AppendChild(textBlock);

Template = new ControlTemplate(typeof(ItemsControl))
{
    VisualTree = stackPanel
};

Équivalent à:

Xaml.svg
<ItemsControl.Template>
    <ControlTemplate TargetType="{x:Type ItemsControl}">
        <StackPanel>
            <ItemsPresenter />
            <TextBlock Text="..." />
        </StackPanel>
    </ControlTemplate>
</ItemsControl.Template>

CommandBindings

Csharp.svg
CommandBindings.Add(new CommandBinding(MyCommand, MyCommandExecuted));

Binding

Csharp.svg
// Binding de la propriété Height d'un Button sur la propriété ActualHeight d'un ItemControl
var binding = new Binding()
{
    // définit la source du Binding
    Source = this.monItemControl,
    // ou bien une source relative
    RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ItemsControl), 1),
    Mode = BindingMode.TwoWay,
    Converter = new MyConverter(),
    Path = new PropertyPath("ActualHeight")
}

button.SetBinding(Button.HeightProperty, binding);

MergedDictionaries

Csharp.svg
var rd = new ResourceDictionary();
rd.Source = new System.Uri("pack://application:,,,/flowers;Component/Resources/Window.xaml");
Resources.MergedDictionaries.Add(rd);

Style

Csharp.svg
var style = FindResource("NomDeMonStyle") as Style;

var textBlockStyle = new Style();
textBlockStyle.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.White));
// le style est ajouté sans clé et sera donc appliqué à tous les TextBlock
Resources.Add(typeof(TextBlock), textBlockStyle);