可重复使用的按钮自定义内容

Sht*_*itz 1 wpf xaml button

我的用户界面使用自定义的Buttons:它们包含a Image和a Label.

Button通过将其内容设置为包含a Image和a 的网格来手动定制单个Label.但是,由于我需要有几个这样的Buttons,不同的图像和标签,我想把这个模式"提取"成可重用的东西.基本上,我只需要一个可重用的对象,有两个属性(ImageText)我可以设置为Content几个Buttons.

我查看了ContentTemplates,但我不需要自定义控件Button本身的外观,只需要自定义它的内容.

最合适的技术是什么?

Dre*_*rsh 5

最简单的方法是为此创建一个UserControl:

  1. 创建UserControl
  2. 将"ImageSource"依赖项属性添加到图像的BitmapSource类型的UserControl类
  3. 将"Text"依赖项属性添加到string类型的UserControl类中
  4. 对于您的UserControl XAML,请放置以下XAML(为简洁起见,您可以根据您的布局需求进行更改)

用户控件的XAML:

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
    <Button>
        <StackPanel Orientation="Horizontal">
           <Image Source="{Binding ImageSource}" />
           <TextBlock Text="{Binding Text}" />
        </StackPanel>
    </Button>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

现在,您可以在任何地方重用您的用户控件,如下所示:

<myNS:MyUserControl ImageSource="MyImages/Foo.png" Text="Click here!" />
Run Code Online (Sandbox Code Playgroud)