WPF以编程方式添加TabItem行为

时间:2016-04-22 08:30:44

标签: c# wpf xaml

在xaml中,当我想添加一些行为时,我喜欢这样:

<!-- XAML -->
<TabItem behaviors:TabItemValidationBehavior.ActivateValidation ="True">
<TabItem.Header>
    <TextBlock Text="Header"                   
               Foreground="{Binding Path=(behavior:TabItemBehavior.Foreground), RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabItem}}}" />
    </TabItem.Header>
</TabItem>

可以通过编程方式进行相同的操作吗?

// C#
TabItem tab = new TabItem();
??tab.AddBehavior(behaviors:TabItemValidationBehavior.ActivateValidation(True));??
??tab.Header= new TextBlock { Foreground.BindTo(behavior:TabItemBehavior.Foreground, tab) };??

如何实现?

1 个答案:

答案 0 :(得分:1)

行为公开AttachedProperty。您可以将其设置为

TabItem tab = new TabItem();
TabItemValidationBehavior.SetActivateValidation(tab, true);

TextBlock text = new TextBlock();
Binding binding = new Binding();
binding.Path = new PropertyPath(TabItemBehavior.ForegroundProperty);
binding.RelativeSource = new RelativeSource{Mode = RelativeSourceMode.FindAncestor, AncestorType = typeof(TabItem)};

text.SetBinding(TextBlock.ForegroundProperty, binding);

tab.Header=text;