0

我的ContextMenu. ItemsSource是 a List<Layer> Layers;,其中类Layer覆盖ToString()以返回Name属性。

如果我不使用任何ItemContainerStyle上下文菜单,一切正常 - 它获取Layer对象并显示该ToString()对象的,就像它应该的那样。当我添加 时ItemContainerStyle,它显示一个空字符串。

这是 XAML:

<Style x:Key="myItemControlTemplate" TargetType="{x:Type MenuItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MenuItem}">
                <Border SnapsToDevicePixels="True" Height="32" Width="200" Background="White">
                    <Grid VerticalAlignment="Center" Height="Auto" Width="Auto" Background="{x:Null}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{TemplateBinding Header}" VerticalAlignment="Top" Foreground="#FF3B3D52"
                                   Grid.Column="1" Margin="6,0,0,0"/>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


<Button ContextMenuService.IsEnabled="False">
    <Button.ContextMenu>
        <ContextMenu FontFamily="Global Sans Serif" Height="Auto" Width="200" Padding="0,6" VerticalOffset="5" BorderThickness="0" 
                     HasDropShadow="True" ItemContainerStyle="{StaticResource myItemControlTemplate}">
        </ContextMenu>
    </Button.ContextMenu>
</Button>

我是这样开火的:

private void btn_Click(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;

    ContextMenu ctm = btn.ContextMenu;
    ctm.ItemsSource = Layers;
    ctm.PlacementTarget = btn;
    ctm.Placement = PlacementMode.Bottom;
    ctm.IsOpen = true;
}

是不是因为某种原因这个绑定以某种方式被破坏了?

Text="{TemplateBinding Header}"

顺便说一句,如果我将图层列表更改为 aList<string>并且只是将图层的名称提供给它,它可以与ItemContainerStyle.

我错过了什么?

4

1 回答 1

0

问题是TemplateBinding. 这是相对源绑定到模板父级的一个不太强大但经过优化的变体,但它以一些限制为代价,例如不支持双向绑定。尽管文档中没有正式说明,但似乎此绑定不支持将基础类型转换为string,因为ToString在这种情况下从未调用过。

使用相对源将 替换为TemplateBinding与模板化父级的绑定。

<TextBlock x:Name="textBlock"
           HorizontalAlignment="Left" TextWrapping="Wrap"
           Text="{Binding Header, RelativeSource={RelativeSource TemplatedParent}}" 
           VerticalAlignment="Top" Foreground="#FF3B3D52"
           Grid.Column="1" Margin="6,0,0,0"/>
于 2021-03-27T12:07:37.763 回答