1
我創建了一個非常簡單的用戶控件,一個ImageButton的Caliburn.micro和用戶控件單擊處理
<UserControl x:Class="SampleApp.Controls.ImageButton"
Name="ImageButtonControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Button>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="6*" />
<RowDefinition Height="2*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Image Grid.Row="1" Source="{Binding ElementName=ImageButtonControl, Path=Image}" VerticalAlignment="Stretch" HorizontalAlignment="Center" />
<TextBlock Grid.Row="2" Text="{Binding ElementName=ImageButtonControl, Path=Text}" VerticalAlignment="Stretch" HorizontalAlignment="Center" />
</Grid>
</Button>
</UserControl>
隨着後面的代碼:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace SampleApp.Controls
{
/// <summary>
/// Interaction logic for ImageButton.xaml
/// </summary>
public partial class ImageButton : UserControl
{
public ImageButton()
{
InitializeComponent();
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ImageButton), new UIPropertyMetadata(""));
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
}
}
現在我想用我的小樣本中應用像
xmlns:controls="clr-namespace:SampleApp.Controls"
<controls:ImageButton Grid.Row="1"
Grid.Column="1"
Margin="2"
Image="/Images/link.png"
Text="DoSomething">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="DoSomething" />
</i:EventTrigger>
</i:Interaction.Triggers>
</controls:ImageButton>
如果我給它斧頭:名稱,像
<controls:ImageButton x:Name="DoSomething"
例如DoSomething方法DoSomething
與該名稱直接調用時顯示視圖,即當我激活包含該按鈕的視圖模型,就像我單擊按鈕(如果它是一個普通的按鈕,而不是一個用戶控件,它會這樣工作),但按鈕單擊處理程序不會在點擊時調用。
現在我想從上面可以看出添加ActionMessage的,但它也不管用...
這裏有什麼問題?
是的好主意,我傾向於使用附加屬性來設置按鈕的圖像;這樣你不需要派生控件來創建模板按鈕,只需要將默認樣式應用於所有按鈕即可。該樣式可以包含一個模板,該模板綁定到該附加屬性,所以按鈕本身不需要知道它 - 這是非常有效的(儘管如果我回想起來,VS2010中的設計器中存在一些問題並綁定到附加屬性 - 工作正常在運行時,雖然) – Charleh 2013-04-05 23:35:08
是的,這種方法效果很好,你還可以使附加屬性具有足夠的通用性,以便支持可以模板化的其他屬性(例如文本,邊框,背景等),以便可以在所有按鈕之間重複使用一個附加屬性模板樣式 – devdigital 2013-04-06 06:38:42
非常感謝,使它成爲一個按鈕而不是一個用戶控件,效果很好。我怎樣才能使通用附加屬性?我不想將圖像添加到每個按鈕,因爲我想要更簡潔的XAML。 – 2013-04-06 08:05:23