开发者

Need to override default ContentTemplate for string content

If I have a Menu defined like this:

<Menu>
<MenuItem Header="Stuff" />
</Menu>

When this gets rendered, the ContentPresenter inside of the MenuItem ends up with content like this:

<TextBlock Text="{Binding}" />

which means that it inherits the default styling of TextBlock, which isn't always desirable.

I know that I can change my MenuItem to be something like:

<MenuItem>
<MenuItem.Header>
<TextBlock Text="Stuff" Style="{DynamiResource MyStyle}" />
</MenuItem.Header>
</MenuItem>

but that would be an annoying requirement.

I know that I can override the default style of MenuItem to explicitely set the ContentTemplate, but that would mean that if the content was something other than a String, or if the specific instance of the MenuItem specified a ContentTemplate, my default style would override that - which would be bad.

I know that somewhere in the magic of WPF, there is a converter or something that is taking the content of type String and creating a DataTemplate that uses a TextBlock,开发者_StackOverflow but I can't find where this is. I figure that there has got to be some way to intercept that magic, but since I can't locate where the magic happens, I can't figure out how to intercept it.

Any ideas?

David Mullin


You could make a DataTemplateSelector returning your custom template for strings but just returning the default for all other types.

public class MenuStringDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate
        SelectTemplate(object item, DependencyObject container)
    {
        if(item is string)
           //TODO return your template
        return base.SelectTemplate(item, container);               
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜