WPF 以编程方式添加具有行为的 TabItem



在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) };??

如何实现?

行为公开一个附加属性。您可以将其设置为这样

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;

最新更新