c# - 为什么TemplateBinding无法绑定(bind)Button.Content?

标签 c# wpf xaml

我是 WPF 新手,我正在执行一些模拟来尝试理解 绑定(bind)“事物”(例如 {Binding}{TemplateBinding} ...)

好的,所以我在这里制作这个示例来测试 TemplateBinding 并且运行良好:

<Button Width="100" Height="100">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Image Source="image.png" Width="{TemplateBinding Width}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

现在我尝试了相同的但具有其他属性:

<Button Width="100" Height="100" Content="image.png">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Image Source="{TemplateBinding Content}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

在第一种情况下,绑定(bind)完美发生。但第二秒什么也没有发生。

我在这里缺少什么?有一些属性可以绑定(bind)其他属性则不能?

我真的迷失了,有人可以向我解释为什么一个有效而另一个无效吗?

最佳答案

TemplateBinding 在编译时进行评估,并且不提供自动值类型转换(在本例中为 stringImageSource)。只需使用 TemplatedParent 相对源绑定(bind)即可

<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />

与此问题没有直接关系的另一件事是,如果您想将 TemplateBinding 用于相同类型的其他属性,请确保相应地设置 TargetTypeTemplateBinding 根据 ControlTemplate 类型进行评估,默认 TargetTypeSystem.Windows.Controls.Control

<ControlTemplate TargetType="{x:Type Button}">

关于c# - 为什么TemplateBinding无法绑定(bind)Button.Content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820440/

相关文章:

c# - WPF 数据网格绑定(bind)问题 : first row bound but doesn't update selected item in two-way fashion

c# - MSMQ:为什么我不能从远程专用队列中检索队列详细信息?

wpf - 使用 WPF 延迟输入验证

c# - WPF:通过应用程序应用样式

c# - WPF 中的低分配绘图

c# - 使用 SelectionMode Multiple/Extended 跨多个嵌套列表框获取所有选定项

.net - WPF/xaml 中动画心跳/示波器效果的明智方法

c# - T4 模板 : Any way to make template run when some class that it uses is modified?

c# - 客户端/服务器握手使用 RestSharp 失败,但在 Postman 和使用 Fiddler 作为代理时工作正常。证书长度 0

c# - 在 Windows 窗体应用程序中覆盖两个面板