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;

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
binding.Source = this.monItemControl;
// ou bien une source relative
binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ItemsControl), 1);
binding.valueBinding.Mode = BindingMode.TwoWay;
binding.Converter = new MyConverter();
binding.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);