我想创建一个内容为图片和文本块的按钮。于是我搜寻了一篇文章(按钮可重用自定义内容),得知可以通过创建一个用户控件来实现。
我按照方法创建了这个用户控件,它能够很好地工作。我可以通过依赖属性设置图片来源和文本。但是,我卡在了无法为我的控件添加点击事件上。
我进行了更多的调查,得出结论可能需要从Button派生一个CustomControl。这样做正确吗?还是将点击事件与我的UserControl连接起来会更好呢?
这是我的UserControl:
<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Button Width="Auto" HorizontalAlignment="Center">
<Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
<Grid>
<Image Name="tehImage" Source="{Binding ImageSource}" />
<TextBlock Name="tehText" Text="{Binding Text}"
Style="{DynamicResource ButtonText}" />
</Grid>
</Border>
</Button>
</UserControl>
实现
<my:MyButton ImageSource="../Images/MainSyncButton.png" ImageWidth="141" Text="Synchronise" Click="btnSynchronise_Click" />