开发者

style setter for WPF context menu

开发者 https://www.devze.com 2023-03-17 04:22 出处:网络
The following code wo开发者_如何学Gorks fine, <ContextMenu ItemsSource=\"{Binding SourceA}\" Visibility=\"{Binding SourceAVisible,Converter={StaticResource BoolToHiddenConverter}}\" />

The following code wo开发者_如何学Gorks fine,

<ContextMenu ItemsSource="{Binding SourceA}" Visibility="{Binding SourceAVisible,Converter={StaticResource BoolToHiddenConverter}}" />

I thought the following code is the equivalent, however it throws a runtime exception saying the items collection must be cleared before using ItemsSource.

<ContextMenu ItemsSource="{Binding SourceA}">
                <Style TargetType="{x:Type ContextMenu}">
                    <Setter Property="ContextMenu.Visibility" Value="{Binding SourceAVisible,Converter={StaticResource BoolToHiddenConverter}}"/>
                </Style>
 </ContextMenu>


    <ContextMenu ItemsSource="{Binding SourceA}">
            <ContextMenu.Style>
                <Style TargetType="{x:Type ContextMenu}">
                    <Setter Property="ContextMenu.Visibility" Value="{Binding SourceAVisible,Converter={StaticResource BoolToHiddenConverter}}"/>
                </Style>
            </ContextMenu.Style>
        </ContextMenu>

if you put anything between the tags of an item it is assumed to be the content (in this case the ItemsSource which is already set). You need to implicitly tell WPF that you are setting the value of the style.


You forgot to wrap <Style> in <ContextMenu.Style>. Therefore, it's trying to add your Style instance as a child of the ContextMenu - that is, to its Items collection. Since you're also setting ItemsSource, that is why you're seeing the exception.

0

精彩评论

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