如何设置子控件的属性

时间:2019-02-14 14:52:05

标签: c# wpf button

我需要很多包含图像和文本的按钮。这就是为什么我不想使用

<Button>
  <Image></Image>
  <TextBlock></TextBlock>
</Button>

因此,我创建了一个新的ImageTextButton

public class ImageTextButton: Button
{ 
  public TextBlock Label
  {
    get { return (Label)GetValue( LabelProperty ); }
    set { SetValue( LabelProperty, value ); }
    }
    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
                                                                       name: nameof( Label ),
                                                                       propertyType: typeof( TextBlock ),
                                                                       ownerType: typeof( ImageTextButton ) );

  public PSImage Image
  {
    get { return (Image)GetValue( ImageProperty ); }
    set { SetValue( ImageProperty, value ); }
    }
  public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
                                                                       name: nameof( Image ),
                                                                       propertyType: typeof( Image ),
                                                                       ownerType: typeof( ImageTextButton) );

  public ImageTextButton()
  {
    StackPanel panel = new StackPanel();
    panel.Children.Add( Image );
    panel.Children.Add( Label );
    panel.Orientation = Orientation.Horizontal;
    Content = panel;
  }

在c#代码中设置文本效果很好,但是否也可以在XAML中输入它?

您能帮我还是给我一个提示?

1 个答案:

答案 0 :(得分:0)

您应该在类中添加string依赖项,而不是Label属性。然后,您可以像这样简单地在XAML中设置控件的属性:

<local:ImageTextButton YourTextProperty="some string.." />

Label元素应在自定义控件的模板中定义,并绑定到string依赖项属性。

ImageTextButton类可能应该是UserContol而不是自定义控件,因为它只是内置控件的组合:

<UserControl ...>
    <Button>
        <Image></Image>
        <TextBlock Text="{Binding YourTextProperty, RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBlock>
    </Button>
</UserControl>

当然,您可以向UserControl添加其他几个依赖项属性,并将它们以相同的方式绑定到XAML中元素的相应属性。

恐怕您无法在XAML中执行类似<local:ImageTextButton LabelProperty.Content="some string.." />的操作。

如果您想要的话,您当然可以像这样为Label元素设置Label依赖项属性:

<local:ImageTextButton>
    <local:ImageTextButton.Label>
        <Label Content="..." /> 
     </local:ImageTextButton.Label>
</local:ImageTextButton>
相关问题