You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF XAML中图像与按钮无法填充网格单元格问题排查

WPF嵌套UserControl+Viewbox布局显示问题

将一个UserControl添加至另一个UserControl内的Viewbox中时,遇到两个显示问题(见截图):

  • 左上角按钮无法填满整个Grid单元格,但其内部图像却填满了按钮。试过多种按钮图像绑定方式,导致它与网格中其他按钮实现不同,但找不到二者的差异点。
  • 顶部、左侧、右侧及底部中间按钮的黑色图像无法填满按钮,但在设计器中显示正常。这些按钮代码和ContentControl中的一致,仅图像路径指向纯黑色图像。

想知道这两个问题是否相关,有没有类似的解决方法?已尝试添加额外Viewbox、设置Stretch为Fill及调整对齐参数,均无效果。

补充代码

父UserControl(Location.xaml)

<Viewbox Grid.Row="1" Grid.Column="1" Grid.RowSpan="2" Margin="10 10 10 10">
    <ContentControl Content="{Binding CurrentLocationViewModel}">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type locationViewModel:SmallRoomViewModel}">
                <locationView:SmallRoomView/>
            </DataTemplate>

            <DataTemplate DataType="{x:Type locationViewModel:LargeRoomViewModel}">
                <locationView:LargeRoomView/>
            </DataTemplate>
        </ContentControl.Resources>
    </ContentControl>
</Viewbox>

子UserControl(SmallRoomView.xaml)

<Grid>
    <Grid.Resources>
        <Button x:Key="wallTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appWallTile}"/>
        <Button x:Key="floorTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appFloorTile}"/>
        <Button x:Key="doorTile" x:Shared="false"  PreviewMouseDown="OnMouseDown" Style="{StaticResource appDoorTile}"/>
    </Grid.Resources>
    
<Button Grid.Row="0" Grid.Column="0" PreviewMouseDown="OnMouseDown">
    <Image Stretch="Fill" Source="{Binding tile0_0}"/>
</Button>

<ContentControl Grid.Row="0" Grid.Column="2" Content="{StaticResource doorTile}"/>
<ContentControl Grid.Row="0" Grid.Column="3" Content="{StaticResource wallTile}"/>
...
</Grid>

全局样式(App.xaml)

<Style x:Key="appDoorTile" TargetType="Button" x:Shared="false">
    <Setter Property="Content">
        <Setter.Value>
            <Image Stretch="Fill" Source="./AllResources/images/tiles/doorTile.png"/>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="appFloorTile" TargetType="Button" x:Shared="false">
    <Setter Property="Content">
        <Setter.Value>
            <Image Stretch="Fill" Source="./AllResources/images/tiles/floors/floorTile.png"/>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="appWallTile" TargetType="Button" x:Shared="false">
    <Setter Property="Content">
        <Setter.Value>
            <Image Stretch="Fill" Source="./AllResources/images/tiles/walls/wallTile.png"/>
        </Setter.Value>
    </Setter>
</Style>

内容的提问来源于stack exchange,提问作者AuthorBrotherGames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:10:13