【问题标题】:Can't bind custom control content (WPF)无法绑定自定义控件内容 (WPF)
【发布时间】:2014-06-24 08:36:21
【问题描述】:

我有一个基于 Button 的简单自定义控件:

<Style TargetType="{x:Type local:ArrowButton}">

    <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
    <Setter Property="BorderBrush" Value="{StaticResource NormalBorderBrush}"/>
    <Setter Property="Focusable" Value="True"/>

    <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ArrowButton}">
                <Grid>
                    <Ellipse Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}"/>
                    <ContentPresenter/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

它没有任何重要的 C# 代码:

public class ArrowButton : Button, IDisposable
{
    static ArrowButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton)));
    }
}

如果我按以下方式使用此控件(在某些 UserControl 中),它可以正常工作(我有两个带有黑色三角形的按钮):

    <Grid.Resources>
        <Style TargetType="local:ArrowButton">
            <Setter Property="Width" Value="30"/>
            <Setter Property="Height" Value="30"/>
        </Style>
    </Grid.Resources>

    <local:ArrowButton Grid.Column="0" HorizontalAlignment="Left">
        <Path HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Black" Data="M  0 0 L 0 20 L 10 10 Z"/>
    </local:ArrowButton>
    <local:ArrowButton Grid.Column="1" HorizontalAlignment="Right">
        <Path HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Black" Data="M  0 0 L 0 20 L 10 10 Z"/>
    </local:ArrowButton>

但如果我将 Path 移动到 StaticResource,我会得到一个奇怪的效果:只有最后一个按钮有黑色三角形,而 UserConltrol 上的所有其他按钮都保持为空(看起来 Path 只绑定了一次)。

    <Grid.Resources>
    <Path x:Key="ArrowPath" Fill="Black" Data="M  0 0 L 0 20 L 10 10 Z"/>
    </Grid.Resources>

    <local:ArrowButton Content="{StaticResource ArrowPath}" Grid.Column="0" HorizontalAlignment="Left"/>
    <local:ArrowButton Content="{StaticResource ArrowPath}" Grid.Column="1" HorizontalAlignment="Left"/>

任何想法,可能有什么问题?

【问题讨论】:

    标签: .net wpf xaml path resources


    【解决方案1】:

    在声明Path 资源时,您需要使用x:Shared="False"

    <Path x:Key="ArrowPath" x:Shared="False" Fill="Black" Data="M  0 0 L 0 20 L 10 10 Z"/>
    

    否则,将使用相同的Path 对象,这将一遍又一遍地更改Path 的视觉父级(直到它停止到最后一个ArrowButton)。设置 x:Shared="False" 将在每次使用 Path 对象时创建一个新实例,这将解决您的问题。

    确保您还阅读了链接页面底部列出的关于在 WPF 中可以使用x:Shared 的位置的限制。

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 2015-06-03
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2011-08-06
      • 2015-07-07
      相关资源
      最近更新 更多