I've implemented a control, CommandTextBox, which I want to be a text box with a button right next to it (so it almost appears within the text box).
The button should be an image which I can bind to an icon. It's fairly straightfoward stuff...
public class CommandTextBox : TextBox
{
/// <summary>
/// The image property.
/// </summary>
public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
"Image", typeof(ImageSource), typeof(CommandTextBox), null);
/// <summary>
/// Initializes a new instance of the <see cref = "CommandTextBox" /> class.
/// </summary>
public CommandTextBox()
{
this.DefaultStyleKey = typeof(CommandTextBox);
}
/// <summary>
/// Gets or sets the image.
/// </summary>
/// <value>
/// The image.
/// </value>
public ImageSource Image
{
get
{
return (ImageSource)this.GetValue(ImageProperty);
}
set
{
this.SetValue(ImageProperty, value);
}
}
}
I have a template as follows...
<Style TargetType="Controls:CommandTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Controls:CommandTextBox">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{TemplateBinding Text}"/>
<Button Grid.Column="1"
Content="Search" >
<Button.Template>
<ControlTemplate>
<Image Source="{TemplateBinding Image}" />
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
But I get an error due to the template binding in the image. I sortof understand why, it's because the Template has changed now so the binding context isn't the same but I don't know how to overcome it.
Do I need to create a seperate ImageButton c开发者_StackOverflow中文版ontrol so I can just do a normal template binding or is there another way?
Thanks Ben
I have managed to get this to work by changing the style as follows:
<Style TargetType="appControls:CommandTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="appControls:CommandTextBox">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{TemplateBinding Text}"/>
<Button Grid.Column="1" >
<Button.Content>
<Image DataContext="{TemplateBinding Image}" Source="{Binding}" />
</Button.Content>
</Button>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I'm not using a seperate template for the Button. My XAML with the control is:
<controls:CommandTextBox Text="Text" Image="/MyApp.Silverlight;component/Assets/Images/Amber_Triangle.png"></controls:CommandTextBox>
This appears to achieve the result you were after. The control renders on my test page as expected.
精彩评论